Convenience methods

Many Cocoa classed provide methods that combine the two stages of allocating and initializing to return temporary instances. Such methods are called convenience methods.

Convenience methods include the name of the class in the method's name. For example, the NSString class provides the +(id)stringWithString:(NSString *)aString convenience method that's similar to the -(id)initWithString:(NSString *)aString initializer method used by the MyCircle class.

When not using automatic garbage collection, the primary difference between calling

[[NSString alloc] initWithString:@"some string"] and

[NSString stringWithString:@"some string"]          //convenience methods

is that the +stringWithString: return an instance that will be automatically deallocated unless you send it a -retain message to prevent deallocation.

When using automatic garbage collection, there is no significant difference between the two techniques for obtaining a new instance.

 

+ (id)stringWithString:(NSString *)aString

{

  return [[[self alloc] initWithString:aString] autorelease];

}

 

 

One drawback to using the convenience methods is that you give up flexibility in the way instances are allocated becasue the allocation technique is hard-coded in the method. ?

 

posted on 2013-02-18 16:01  Chansonyan  阅读(196)  评论(0)    收藏  举报

导航