SpokaneDude
SpokaneDude

Reputation: 4974

Class not being added to NSMutableArray.. why?

I have a class defined with five (5) properties. I want to take those properties and place them in a NSMutableArray (listOfSites). This is my code:

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];

The sArray (not an array, but the name of the class) has the correct content, but the "addObject: sa" message does NOT place the class into the class.

What am I doing wrong?

UPDATE: declaration of "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

}

Initialization of "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; 
}

Upvotes: 0

Views: 116

Answers (1)

sch
sch

Reputation: 27506

You are using two different variables named listOfSites. The first one is a local variable in didFinishLaunchingWithOptions:

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

The second one is an instance variable one the class slSQLite:

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

When you initialize the variable listOfSites that is in didFinishLaunchingWithOptions,, the there variable that is in slSQLite remains unchanged and non initialized.

So you should initialize the array before using it:

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 is an object and not a class. It is an instance of the class sArray.

Upvotes: 1

Related Questions