Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 使用对象填充NSMutableSet不工作-NSLog和调试器显示Null_Objective C_Ios_Xcode4.2_Nsset_Nsmutableset - Fatal编程技术网

Objective c 使用对象填充NSMutableSet不工作-NSLog和调试器显示Null

Objective c 使用对象填充NSMutableSet不工作-NSLog和调试器显示Null,objective-c,ios,xcode4.2,nsset,nsmutableset,Objective C,Ios,Xcode4.2,Nsset,Nsmutableset,我正在尝试使用NSMutableSet创建一组对象。对象是一个标记,每个标记都有一个id和一个名称 标记类的定义如下: #import "Tag.h" @implementation Tag @synthesize id, name; +(id) populateTagObjectWithId:(NSString *)id andName:(NSString *)name { Tag *myTag = [[self alloc] init]; myTag.id = id;

我正在尝试使用NSMutableSet创建一组对象。对象是一个标记,每个标记都有一个id和一个名称

标记类的定义如下:

#import "Tag.h"

@implementation Tag

@synthesize id, name;

+(id) populateTagObjectWithId:(NSString *)id andName:(NSString *)name
{
    Tag *myTag = [[self alloc] init];
    myTag.id = id;
    myTag.name = name;

    return myTag;
}
... remainder of code snipped out
在我的应用程序的其他地方,我使用SQLite获取标记表中的标记。我使用while循环进行迭代,每次迭代我都构建一个标记对象,然后尝试将其添加到集合中。代码如下:

... previous code snipped out...
NSMutableSet *thisTagSet;

while(sqlite3_step(tag_statement) == SQLITE_ROW)
{
    NSString *thisTagId     = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(tag_statement, 0)];
    NSString *thisTagName   = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(tag_statement, 1)];

    [thisTagSet addObject:[Tag populateTagObjectWithId:thisTagId andName:thisTagName]];

    ... rest of code snipped out...
因此,正如我所提到的,当我迭代这个while循环时,我得到了对象及其id和名称正在填充(我通过检查调试器并使用NSLog确认了这一点)。然而,thisTagSet NSMutableSet仍然是空的,即使我使用的是addObject方法。我有什么地方做错了吗?我也试着将这两个步骤分开,如下所示:

Tag *thisTagObject = [Tag populateTagObjectWithId:thisTagId andName:thisTagName];
[thisTagSet addObject:thisTagObject];

同样的结果。我成功地获取了一个thisTagObject,但thisTagSet中没有任何内容…

在阅读您的代码后,会弹出两个内容:

您没有初始化NSMutableSet,并且通过在类方法中返回保留对象泄漏了标记

编辑:添加泄漏修复代码

+(id)tagObjectWithId:(NSString *)id andName:(NSString *)name
{
    Tag *myTag = [[self alloc] init];
    myTag.id = id;
    myTag.name = name;

    return [myTag autorelease];
}

第二次编辑:上述代码仅在禁用ARC时适用。否则它就不需要了,因为ARC负责内存管理。

您是使用
-[NSMutableSet new]
或其他初始化方法来初始化您的集合的吗?NSMutableSet*thisTagSet=[[NSMutableSet alloc]init]---成功了!我怎么会忽视这一点?万分感谢!谢谢你的回答,是的,我已经解决了初始化问题。如何修复内存泄漏?在
+populateTagObjectWithId:andName:
方法中使用autorelease。像这样:
return[anist autorelease]
再次感谢您的反馈,不过我使用的是ARC。ARC禁止使用自动释放,因为它不再需要(据我所知)。在ARC下,没有必要像你所说的那样释放,泄漏也不会发生。