I am quite new to programming and objective C and I am having a hard time grasping a concept here about allocation, memory management and how they tie in with instance variables. I created a category for NSString called isUrl to test for a prefix of "http:// in a string.
From there, I wanted to test this on a string. However, given that situation I couldn't figure out if I should: 1) Declare a new string as an instance variable with @property to synthesize the accessors 2) Allocate a new string in my implementation 3) Set my variable and allocate it
What would be the difference between these methods and why would I perhaps want to use one over the other? -
As a side note, I am working with a book by O'Reilly and have tried to find answers around the web, but not a lot of luck thus far. I seem to find examples of everything, but I an explanation of how or why they are used is more difficult.
1)
NSString* 开发者_JAVA技巧string = [[[NSString alloc]init]autorelease];
string = @"http://www.google.com";if ( [string isUrl]) { NSLog(@"Caption is a URL"); NSLog(@"URL %@",string); string = nil;
2)
NSString* string = @"http://www.googl.com"; [string retain]; if ( [string isUrl]) { NSLog(@"Caption is a URL"); NSLog(@"URL %@",string); string = nil;
3) Something like this....
@synthesize string; string.name = "http://www.google.com"; if ( [string.name isUrl]) { NSLog(@"Caption is a URL"); NSLog(@"URL %@",string); string = nil;
String literals don't need to be released or retained.
Properties should be used whenever a value associated with an object needs to exist outside of a single function call and you don't need your program to compile under 10.4 or earlier. By your use of nil
, it appears you don't need the string to persist, so you should only use a local variable. That's what local variables are for.
NSString* string = @"http://www.google.com";
if ( [string isUrl]) {
NSLog(@"Caption is a URL");
NSLog(@"URL %@",string);
}
Apple's Objective-C memory management rules are quite simple. There's really only one rule, with a couple of corollaries.
NSString* string = [[[NSString alloc]init]autorelease]; string = @"http://www.google.com";
You don't need to allocate an object before assigning a different object to the same variable. The first object will simply get deallocated and serves no purpose.
string.name = "http://www.google.com";
"" denotes a C string. For an NSString, you must use the at symbol. The above should be
string.name = @"http://www.google.com";
精彩评论