类没有添加到NSMutableArray ..为什么?

时间:2012-03-19 21:30:33

标签: objective-c nsmutablearray

我有一个定义了五(5)个属性的类。我想获取这些属性并将它们放在NSMutableArray(listOfSites)中。这是我的代码:

FMResultSet *rs = [fmdb executeQuery: @"SELECT SITE_ID, SITE_DESC, DATE FROM SiteData WHERE SITE_ID <> '0'"];
while([rs next])  {
    sArray *sa = [[sArray alloc] init];
    sa.sSiteID = [rs stringForColumnIndex:0];
    sa.sJobDesc = [rs stringForColumnIndex:1];
    sa.sJobDate = [rs stringForColumnIndex:2];

    [listOfSites addObject:sa];  //  add class object to array
}
[fmdb close];

sArray(不是数组,但类的名称)具有正确的内容,但“addObject:sa”消息不会将类放入类中。

我做错了什么?

更新:“listOfSites”的声明:

@interface slSQLite : NSObject  {

    sqlite3 *dataBase;  //  declare pointer to database
    UILabel *status;
    BOOL newFlag;
    int siteCount;
    int seqNbr;
    NSDate *date;
    NSString *dbCmd;
    NSMutableArray *listOfSites;  //  populated by sqlite

}

“listOfSites”的初始化:

@implementation slAppDelegate  {   }

@synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  {

    slSQLite *sqlite = [[slSQLite alloc] init];  //  allocate class
    [sqlite checkForDatabase];  //  check for database

    NSMutableArray *listOfSites = [[NSMutableArray alloc] init];

    return YES; 
}

1 个答案:

答案 0 :(得分:1)

您正在使用名为listOfSites的两个不同变量。第一个是didFinishLaunchingWithOptions中的局部变量:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  {
    //...
    NSMutableArray *listOfSites = [[NSMutableArray alloc] init];
    //...
}

第二个是类slSQLite的实例变量:

@interface slSQLite : NSObject {
    // ...
    NSMutableArray *listOfSites;  //  populated by sqlite
}

初始化listOfSites中的变量didFinishLaunchingWithOptions时,slSQLite中的变量保持不变且未初始化。

所以你应该在使用之前初始化数组:

listOfSites = [[NSMutableArray alloc] init];
while([rs next])  {
    sArray *sa = [[sArray alloc] init];
    sa.sSiteID = [rs stringForColumnIndex:0];
    sa.sJobDesc = [rs stringForColumnIndex:1];
    sa.sJobDate = [rs stringForColumnIndex:2];

    [listOfSites addObject:sa];
}
NSLog(@"The array listOfSites contains %d items, listOfSites.count);

PS。 sa是一个对象,而不是一个类。它是类sArray的一个实例。