I want to create a utility class with common functions I need. So they have to be static, and not leak memory.
Say I wanted to add this function that converts a NSString to a NSNumber:
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:@"42"];
[f release];
How could I return the result, and not leak?
Would i have to use autorelease for this?
Use autorelease to avoid memory leaks when returning objects with uncertain ownership.
NSNumber‘snumberFromString:method returns an autoreleased value already, so you do not need to do anything special in your case. With objects of other classes, you can do this:Note that if you use ARC you do not need to do any of this: the compiler is smart enough to figure most of it out for you.
In Objective C static methods of Java/C++/C# are called class methods. You denote them with a
+instead of-in the declaration, and remember that you cannot access instance methods from the implementation.In the header:
In the implementation: