문제

I am trying to create a set of objects using NSMutableSet. The object is a tag, each tag has an id and a name.

The tag class is defined like so:

#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

Somewhere else in my application I use SQLite to fetch tags in the TAG table. I iterate using a while loop, for each iteration I build a tag object and then try to add it to the set. Code below:

... 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...

So, as I mentioned, as I iterate through this while loop, i get the object and its id and name ARE populating (I have confirmed this by inspecting the debugger and also using NSLog). The thisTagSet NSMutableSet however remains empty even though I'm using the addObject method. Is there something I'm doing wrong here? I have also tried separating out the two steps like so:

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

Again, the same result. I successfully get a thisTagObject, but nothing in the thisTagSet...

도움이 되었습니까?

해결책

After reading your code two things pop out:

You're not initializing your NSMutableSet, and you're leaking your tags by returning a retained object in your class method.

Edit: Added leak-fix code

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

    return [myTag autorelease];
}

2nd edit: The code above only applies as long as ARC is disabled. Otherwise it is not needed as ARC takes care of the memory management.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top