开发者

Proper way of setting NSString in Singleton?

In my "User" singleton, I have the following method:

- (void)updateUser:(NSDictionary*)userInfo
{
    //uid, fullname, email are ivars
    [uid release];
    uid = [[NSString alloc] initWithString:[userInfo objectForKey:@"id"]];
    [fullName release];
    fullName = [[NSString alloc] initWithFormat:@"%@ %@", [userInfo objectForKey:@"fname"], [userInfo objectForKey:@"lname"]];
    [email release];
    email = [[NSString alloc] initWithString:[userInfo objectForKey:@"email"]];
}

Is this the proper way to set NSStrings? I tried using autorelease objects but they seem t开发者_高级运维o be releasing too early.

Edit: Nevermind I'm dumb. Completely forgot about NSMutableStrings


You haven't given much information but that's essentially how you create NSString objects and assign them to what is possibly instance variables in your singleton. The thing that you may want to watch out for is that you're releasing the old objects before assigning a new one to the variable. Something could potentially go very bad if something accessed that variable between the release and the assignment. Unless you have to support Objective-C before 2.0 I would suggest using synthesized properties since they handle such memory issues securely for you.

Autoreleasing an object basically means that the object is released automatically at a later point. You would use autorelease in situations where you allocate an object but have no ability to release it yourself, such as in a convenience allocation method like this:

+ (id)newObject
{
    return [[[MyClass alloc] init] autorelease];
}

The memory management guidelines says that whoever allocates (or retains) an object should also release it once it no longer needs access to that object. Therefore, autorelease allows a method to return a newly created object and say that it no longer needs it. The caller would have to retain it if it needs it to stay around. If it don't it will just release automatically after the caller goes out of scope.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜