NSMutableArray Init麻烦

时间:2011-08-18 06:15:58

标签: ios objective-c cocoa-touch nsmutablearray nsarray

我有这个方法处理一些我似乎无法正确的数组。与alloc和init相关的东西。

- (void)addBookmark
{
    // Get the user defaults object
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    // Load your bookmarks (editable array)
    NSMutableArray *bookmarks = [[NSMutableArray alloc]init];
    NSArray *bookmarksLoaded = [userDefaults arrayForKey:@"bookmarks"];
    if (bookmarksLoaded != nil) {
        [bookmarks initWithArray:bookmarksLoaded];
    } else {
        [bookmarks init];
    }

    // Add a bookmark
    NSMutableDictionary *bookmark = [NSMutableDictionary new];
    [bookmark setValue:@"value" forKey:@"name"];
    [bookmark setValue:@"value" forKey:@"description"];
    [bookmark setValue:@"value" forKey:@"code"];
    [bookmarks addObject:bookmark];

    // Save your (updated) bookmarks
    [userDefaults setObject:bookmarks forKey:@"bookmarks"];
    [userDefaults synchronize];

    // Memory cleanup
    [bookmarks release];
}

2 个答案:

答案 0 :(得分:5)

你是对的 - 这是你对alloc / init的使用。您应该只init一次对象。你想要这样的东西:

// Load your bookmarks (editable array)
NSMutableArray *bookmarks = nil; // we'll initialize it later
NSArray *bookmarksLoaded = [userDefaults arrayForKey:@"bookmarks"];
if (bookmarksLoaded) { // shortcut for bookmarksLoaded != nil
    bookmarks = [[NSMutableArray alloc] initWithArray:bookmarksLoaded];
} else {
    bookmarks = [[NSMutableArray alloc] init];
}

// Add a bookmark
NSMutableDictionary *bookmark = [NSMutableDictionary dictionary];

如果您使用dictionary而不是new,则会获得一个您不必担心的自动释放对象(Cocoa中未使用new)。正如你所知,你正在泄露记忆。

答案 1 :(得分:1)

NSMutableArray *bookmarks = [[NSMutableArray alloc]init];
NSArray *bookmarksLoaded = [userDefaults arrayForKey:@"bookmarks"];
if (bookmarksLoaded != nil) {
    [bookmarks initWithArray:bookmarksLoaded];
} else {
    [bookmarks init];
}

上面代码的问题是你在任何地方都在创建书签。目标C中的任何对象都必须被引用一次..我会将你的代码重写为

NSMutableArray *bookmarks = nil;
NSArray *bookmarksLoaded = [userDefaults arrayForKey:@"bookmarks"];
if (bookmarksLoaded != nil) {
    bookmarks            = [[NSMutableArray alloc] initWithArray:bookmarksLoaded];
} else {
    bookmarks     =  [[NSMutableArray alloc] init];
}

此外,您必须发布NSMutableDictionary书签,因为您是通过new ..

创建的
NSMutableDictionary *bookmark = [NSMutableDictionary new];
[bookmark setValue:@"value" forKey:@"name"];
[bookmark setValue:@"value" forKey:@"description"];
[bookmark setValue:@"value" forKey:@"code"];
[bookmarks addObject:bookmark];
 [bookmark release];

此外,从代码中可以了解到你还没有掌握iphone中的内存管理。要成为一名成功的iOS开发人员,你必须首先研究它......