Memory Management Objective-C - objective-c

I don't understand why memory consumption increases and never gets released (the project is using ARC) when performing the following operations in my program (please bear with me, I'm at a basic level with plain C):
Simplified: somewhere in my program (AppDelegate for example) I call a macro which basically is a C function with variable parameters which calls other C functions that are returning some NSStrings.
These are defined and implemented in an Objective-C style class and are used together with a singleton object.
Header:
#interface MyClass : NSObject
#end
void func_1(aTypeDef paramType, NSString *input, ...);
void* func_2(NSString *arg1, NSString *arg2, NSString *arg3);
NSString* string_func_1 (void);
NSString* string_func_2 (int anInt);
NSString* string_func_3 (const char *aString);
#define F2_MACRO func_2( \
string_func_1(), \
string_func_2(anINT), \
string_func_3(aSTRING), \
)
#define F1_MACRO(input, ...) func_1(A_TYPE, input, ##__VA_ARGS__, F2_MACRO)
Implementation:
#import "MyClass.h"
static NSString *STRING_1;
static NSString *STRING_2;
static NSString *STRING_3;
#implementation MyClass
void func_1(aTypeDef paramType, NSString *input, ...) {
va_list args;
va_start(args, input);
NSString *output = [[NSString alloc] initWithFormat:input arguments:args];
fputs([output UTF8String], stdout);
va_end(args);
}
void* func_2(NSString *arg1, NSString *arg2, NSString *arg3) {
STRING_1 = arg1;
STRING_2 = arg2;
STRING_3 = arg3;
return NULL;
}
NSString* string_func_1 (void) {
return [NSString stringWithFormat:#"aString"];
}
NSString* string_func_2 (int anInt) {
return [NSString stringWithFormat:#"%d",anInt];
}
NSString* string_func_3 (const char *aString) {
return [NSString stringWithUTF8String:aString];
}
#end
Every time I call the F1_MACRO() in another Objective-C class like AppDelegate memory usage increases every time the string_func_1, string_func_2, string_func_3 return.
I'm sure that my logic and implementation are flawed and I'll appreciate any help.

func_1() is creating a non-autoreleased object.
• If you are using Automatic Reference Counting (ARC), not autoreleasing the object is fine, however it can still lead to apparent memory accretion. Specifically, if you don't have an explicitly #autoreleasepool{} or are not running an event loop on the thread that is calling that function, then the autoreleased object will never be released.
• If you aren't using ARC, then that is a straight up leak. Add [output release]; at the end of the func_1() function.

Related

How to return string array in objective c

I am trying to get data from web service and adding it into nsmutablearray,
after that i want to return that array from extern c function.....
for example:
#implementation SampleClass
-(NSMutableArray* ) createArray:
{
NSMutableArray *array=[NSMutableArray new];
//
//add value in array
//
return array;
}
#end
extern 'C'
{
//how can i
NSArray* returnArray()// this method should return string array
{
SampleClass *sc=[[SampleClass alloc]init];
NSMUtableArray* a=[NSMutableArray new];
a=[sc createArray];
return a
}
}
#end
Why would you need to use extern "C" since Objective-C is a superset of C? You can already use C code without problems.
For your question it depends on lifetime of the array. If the array is retained then this is enough:
char *cString = [[array objectAtIndex:i] UTF8String];
Otherwise you'd need to allocate a new char* for each string, for example by using strdup:
char *cString = strdup([[array objectAtIndex:i] UTF8String]);
Mind that the latter will require you to release memory when you longer need it with free(cString). If you need to return a C array then you will create it before and set values accordingly, eg
char** cArray = calloc([array count], sizeof(char*));

__unsafe_unretained in struct

Let say I have a struct in which I declare like so:
struct myStruct
{
NSString *aString;
}
The above gives error.
I can, however, fix the error by:
struct myStruct
{
__unsafe_unretained NSString *aString;
}
It silences the error, but will crash at runtime, because I suppose aString is immediately released.
I have tried __strong instead but it won't compile.
Is there any other way I can store an object within the struct and use it properly?
You can create a new object and use this as a pointer to a struct (as this is what a Objective C object is). So if you create a subclass of NSObject with instance variables that you require you can treat it exactly like a pointer to a structure (once you have initialised it). i.e.
myObj = [[myObjClass alloc] init];
myObj->instanceVariable1 = #"myString";
As mentioned in the comments below you need to declare the variables in the interface like this:
#interface myObjStruct : NSObject
{
#public
NSString *instanceVariable1;
}
With an NSString you can use a CFStringRef instead, or cast your NSString * to a CFString and retain it with a CFRetain(), or use CFBridgingRetain to get the incremented retain count immediately. You can do this with any type that is toll free bridged from a CF type (such as CFArray CFDictionary).
struct testStruct {
CFStringRef str;
};
- (void)aMethod
{
NSString *string = #"Hello struct";
struct testStruct test = {
CFBridgingRetain(string),
};
}
You now have ownership of the string, and will need to call CFRelease on the test.str at some point to not leak memory. To get a NSString back you cast it like this NSString *string = (__bridge NSString *)test.str;.
The above code has incremented the retain count of the string object. It's possible to get this to work for any object like this:
struct testStruct {
__unsafe_unretained AnyObj *obj;
};
- (void)aMethod
AnyObj *aObj = [[AnyObj alloc] init];
CFBridgingRetain(aObj); \\increment the retain count.
struct testStruct test = {
aObj,
};
aObj = nil;
NSLog(#"%#", aObj);
}
To release this object later you would need to do CFRelease((__bridge CFTypeRef)(test.obj));. Note that if you remove the CFBridgingRetain(aObj); this code will probably crash.
You could also try having a play with id objc_retain(id value); Although to use this you will need to manually include the arc.h header see How to import objc_retainAutoreleasedReturnValue? you would use this to increment the retain value much like the code above but without the need for casting. You'd also have to use the equivalent release function.
Toll-Free Bridged Types
__bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.
__bridge_retained or CFBridgingRetain casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to you. You are
responsible for calling CFRelease or a related function to relinquish
ownership of the object.
__bridge_transfer or CFBridgingRelease moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC. ARC is responsible
for relinquishing ownership of the object.
Example (not recommend)
It seems __bridge_retained, __bridge_transfer don't allow ownership transfer to/from same type. So I used additional __bridge for type casting.
I've test confirmed NSString objects are released without leaks.
#define TEST_COUNT 10000
struct myStruct
{
NSString* __unsafe_unretained aString;
};
static struct myStruct* myArray = NULL;
static void allocString()
{
myArray = (struct myStruct*) malloc(sizeof(struct myStruct) * TEST_COUNT);
for (int i=0; i<TEST_COUNT; ++i)
{
NSString* v = [[NSString alloc] initWithFormat:#"%d", i];
myArray[i].aString = (__bridge NSString*)(__bridge_retained void*) v;
}
}
static void freeString()
{
if (myArray)
{
for (int i=0; i<TEST_COUNT; ++i)
{
if (myArray[i].aString)
{
NSString* v = (__bridge_transfer NSString*) (__bridge void*) myArray[i].aString;
v = nil;
}
}
free(myArray);
}
}

Can non-alphanumeric characters be used as selectors?

The following code compiles and runs fine (note the sel_registerName("+")):
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <objc/message.h>
#interface Integer : NSObject
{
NSInteger intValue;
}
#property (assign) NSInteger intValue;
#end
#implementation Integer
#synthesize intValue;
- (id) plus:(Integer*)anInteger
{
Integer* outInt = [Integer new];
[outInt setIntValue: intValue + [anInteger intValue]];
return outInt;
}
#end
int main (int argc, char const *argv[])
{
id pool = [[NSAutoreleasePool alloc] init];
SEL plusSel = sel_registerName("+");
Method m = class_getInstanceMethod([Integer class], #selector(plus:));
class_addMethod([Integer class], plusSel, method_getImplementation(m), method_getTypeEncoding(m));
Integer* i4 = [Integer new];
Integer* i20 = [Integer new];
[i4 setIntValue: 4];
[i20 setIntValue: 20];
Integer* res = objc_msgSend(i4, plusSel, i20);
NSLog(#"%d + %d = %d", [i4 intValue], [i20 intValue], [res intValue]);
// >> 4 + 20 = 24
[pool drain];
return 0;
}
Other than "yuck", are there reasons to be cautious about doing this?
The API to the ObjC runtime is unlikely to change, but the validity of calling sel_registerName("+") might. I've monkeyed around in the ObjC runtime a lot, and haven't run into any problems even after many updates. That being said, I wouldn't base a multimillion dollar business on this continuing to work forever.
Currently, the Objective-C runtime library doesn't perform any checks on the content of the string you are trying to register and it's unlikely that the development team change that behavior. If it is a non-empty C string, if you always use objc_msgSend to send messages for that selector and if you don't try to do something like [i4 +:i20] (which is going to cause a compiling error), there is no reason to be afraid.
Registered Objective-C selectors are actually C strings stored internally by the runtime system. The runtime system keeps a table of pointers to C strings, the so-called SEL set. When you call sel_registerName the ObjC runtime system calls strcmp for your string and for each C string stored in the SEL set. If any of the C strings in the SEL set is equal to the one you want to register, the function returns the address of the corresponding C string in the set. Otherwise, the system duplicates your string (with strdup), stores the resulting pointer in the SEL set and returns it. This new pointer becomes a new unique selector.

Get property name as a string

I need a way to pass a property and get the name assigned to it. Any suggestions?
#property (nonatomic, retain) MyObject *crazyObject;
NSString *str = SOME_WAY_TO_GET_PROPERTY_NAME(crazyObject);
// Above method should return #"crazyObject"
You can try this:
unsigned int propertyCount = 0;
objc_property_t * properties = class_copyPropertyList([self class], &propertyCount);
NSMutableArray * propertyNames = [NSMutableArray array];
for (unsigned int i = 0; i < propertyCount; ++i) {
objc_property_t property = properties[i];
const char * name = property_getName(property);
[propertyNames addObject:[NSString stringWithUTF8String:name]];
}
free(properties);
NSLog(#"Names: %#", propertyNames);
It's as simple as this...expanding upon what Chuck already mentioned:
#ifndef STR_PROP
#define STR_PROP( prop ) NSStringFromSelector(#selector(prop))
#endif
You then use it like so:
NSString *strProp = STR_PROP(myProperty);
Background
Keep in mind that properties are really just, to quote Apple, "a syntactical shorthand for declaring a class’s accessor methods." In fact, by itself, the #property declaration doesn't even work. Your #synthesize statement translates the #property into the equivalent of two methods:
- (void)setCrazyObject:(MyObject *)something;
- (MyObject *)crazyObject;
Which one is used depends on the context surrounding your self.crazyObject. (#synthesize also creates a matching instance variable if you didn't do it yourself.) The offshoot of all this is that you can't really translate to and from a property with one single method.
Proposed Solution
You can use what Apple already provides:
NSString *foo = NSStringFromSelector(#selector(myClassProperty));
Or do something custom:
Given that self.crazyObject really translates to either [self crazyObject] or [self setCrazyObject:foo] by the time your code is running, ou'll probably need two methods, like:
- (NSString *)setterStringForProperty:(SEL)prop;
- (NSString *)getterStringForProperty:(SEL)prop;
You might then want at least 2 companion methods such as:
- (SEL)setterForPropertyName:(NSString *)propString;
- (SEL)getterForPropertyName:(NSString *)propString;
Within these methods, you can use the Foundation functions NSStringFromSelector and NSSelectorFromString to convert back and forth between SEL and NSString. Use whatever string manipulations you like to convert back and forth between your setter string (setCrazyObject) and your property name (crazyObject).
A complete solution is hard to provide without knowing the exact use case, but hopefully this provides some more clues for anyone trying to accomplish something similar. There might even be some useful things made possible by combining this approach with Oscar's answer.
Here is a function that returns the name of an ivar, so basically it not only returns the properties but any ivar of the class. I haven't found a way to get the property directly so I used the ivar trick.
#import <objc/objc.h>
/// -----
- (NSString *)nameOfIvar:(id)ivarPtr
{
NSString *name = nil;
uint32_t ivarCount;
Ivar *ivars = class_copyIvarList([self class], &ivarCount);
if(ivars)
{
for(uint32_t i=0; i<ivarCount; i++)
{
Ivar ivar = ivars[i];
id pointer = object_getIvar(self, ivar);
if(pointer == ivarPtr)
{
name = [NSString stringWithUTF8String:ivar_getName(ivar)];
break;
}
}
free(ivars);
}
return name;
}
After searching and debugging i find solution for me...
Added #import <objc/runtime.h>
Methods object_getIvar(id obj, Ivar ivar) send bad access and app crashes. i modify some code and it worked great:
+(NSString*)stringWithProperty:(id)property withClass:(id)controller
{
NSString *name = nil;
uint32_t ivarCount;
Ivar *ivars = class_copyIvarList([controller class], &ivarCount);
if(ivars)
{
for(uint32_t i=0; i<ivarCount; i++)
{
Ivar ivar = ivars[i];
name = [NSString stringWithUTF8String:ivar_getName(ivar)];
if ([controller valueForKey:name] == property)
{
break;
}
}
free(ivars);
}
return name;
}
Modifying the solution, it works when your object is allocated already, otherwise it returns nil:-
NSString * NSStringFromProperty(NSObject* property, NSObject* class)
{
unsigned int propertyCount = 0;
objc_property_t * properties = class_copyPropertyList([class class], &propertyCount);
NSString *name = nil;
for (unsigned int i = 0; i < propertyCount; ++i)
{
name = [NSString stringWithUTF8String:property_getName(properties[i])];
NSObject *object = [class valueForKey:name];
if (object != nil && object == property)
{
break;
}
else
{
name = nil;
}
}
free(properties);
return name;
}
You can use
NSString *str = NSStringFromSelector(#selector(crazyObject));
The good thing about this approach is that:
Xcode will autocomplete word crazyObject for you.
When later on you will change the property name from crazyObject to myCrazyObject, Xcode will add a warning saying "unrecognized selector!" -- pretty good for debugging.
I use this method so often, that I even created a function, which allows to write less letters:
NSString * __nonnull sfs(SEL __nonnull theSelector)
{
if (!theSelector)
{
abort();
}
return NSStringFromSelector(theSelector);
}
Now your final solution can look like this:
NSString *str = sfs(#selector(crazyObject));
From Get property name as string, without using the runtime reference library, just define:
#define propertyKeyPath(property) (#""#property)
#define propertyKeyPathLastComponent(property) [[(#""#property) componentsSeparatedByString:#"."] lastObject]
And then you can do something like this:
NSLog(#"%#", propertyKeyPathLastComponent(appleStore.storeLocation.street)); //result: street
You may check my approach at Gist to get the string for a property with autocompletion and compile-time check.
How to use:
Get the property name for a class:
#interface AnyClass : NSObject
#property (strong) NSData *data;
#end
// == My approach ==
// C string for a class
PropertyNameForClass(AnyClass, data); // ==> "data"
// NSString for a class
PropertyStringForClass(AnyClass, data); // ==> #"data"
// Bad approach (no autocompletion; no compile-time check):
NSString *propertyName = #"data";
Get the property name for a protocol:
#protocol AnyProtocol
#property (strong) NSDate *date;
#end
// C string for a protocol
PropertyNameForProtocol(AnyProtocol, date); // ==> "date"
// NSString for a protocol
PropertyStringForProtocol(AnyProtocol, date); // ==> #"date"
Unconventional, hacky, ugly, late, but... as strong-named as it gets and works like a charm:
#define SOME_WAY_TO_GET_PROPERTY_NAME(p) p == p ? [[[[[[[NSString alloc] initWithCString:#p encoding:NSUTF8StringEncoding] componentsSeparatedByString:#"."] lastObject] componentsSeparatedByString:#" "] lastObject] stringByReplacingOccurrencesOfString:#"]" withString:#""] : #""
Sample usage:
NSLog(SOME_WAY_TO_GET_PROPERTY_NAME(self.customer.surname)); // surname
NSLog(SOME_WAY_TO_GET_PROPERTY_NAME([[self customer] birthDate])); // birthDate
...

Anyway to get string from variable name?

Say I have my class
#interface Person : NSObject { NSString *name; }
I need to get the name of NSString's within my class
Person *person = [[Person alloc] init];
NSLog(#"Name of variable %s\n", _NameofVariable_(person->name));
Thanks for the answers, here's the solution I came up from the replies
//returns nil if property is not found
-(NSString *)propertyName:(id)property {
unsigned int numIvars = 0;
NSString *key=nil;
Ivar * ivars = class_copyIvarList([self class], &numIvars);
for(int i = 0; i < numIvars; i++) {
Ivar thisIvar = ivars[i];
if ((object_getIvar(self, thisIvar) == property)) {
key = [NSString stringWithUTF8String:ivar_getName(thisIvar)];
break;
}
}
free(ivars);
return key;
}
As easy as
#define VariableName(arg) (#""#arg)
Then you do:
NSObject *obj;
NSString *str = VariableName(obj);
NSLog(#"STR %#", str);//obj
You can get the names of a class's instance variables with the Objective-C runtime API function class_copyIvarList. However, this is rather involved, rarely done and almost never the best way to accomplish something. If you have a more specific goal in mind than mere curiosity, it might be a good idea to ask about how to accomplish it in Objective-C.
Also, incidentally, person.name doesn't specify an instance variable in Objective-C — it's a property call. The instance variable would be person->name.
You might use preprocessor stringification and a bit of string twiddling:
NSUInteger lastIndexAfter(NSUInteger start, NSString *sub, NSString *str) {
NSRange found = [str rangeOfString:sub options:NSBackwardsSearch];
if(found.location != NSNotFound) {
NSUInteger newStart = NSMaxRange(found);
if(newStart > start)
return newStart;
}
return start;
}
NSString *lastMember(NSString *fullName) {
if(!fullName) return nil;
NSUInteger start = 0;
start = lastIndexAfter(start, #".", fullName);
start = lastIndexAfter(start, #"->", fullName);
return [fullName substringFromIndex: start];
}
#define NSStringify(v) (##v)
#define _NameofVariable_(v) lastMember(NSStringify(v))
If the person object is exposed as a property of the class, you can use objc_msgSend to get the value.
So, if you could access person using
[object person]
You could also do
objc_msgSend(object, "person")
For more details on message sending, including how to pass arguments to methods, see the Objective-C Runtime Programming Guide section on Messaging
The following works as a macro:
#define STRINGIZE(x) #x