首页 > 代码库 > 项目中遇到的问题解决:深刻认识到类的初始化

项目中遇到的问题解决:深刻认识到类的初始化

-(NSArray *)getdataFromDatabase
{
    NSString *path = [self getDBPath];
    NSLog(@"path ==== %@",path);
    NSLog(@"self.getDBPath == %@",[self getDBPath]);
    
    FMDatabase *membersDB = [FMDatabase databaseWithPath:path];
    if (![membersDB open]) {
        NSLog(@"Failed to open membersDB");
        return nil;
        [membersDB close];
    }
    NSMutableArray *array = [NSMutableArray array];
    FMResultSet *rs = [membersDB executeQuery:@"SELECT * FROM Member"];//这里数组为空  容易出错
    <pre name="code" class="objc">    <span style="color:#FF0000;">
    Member *member = [[Member alloc]init];
    while ([rs next])
    { member.name = [rs stringForColumn:@"Name"]; 
      member.age = [rs intForColumn:@"Age"]; 
      member.sex = [rs intForColumn:@"Sex"];
      member.height = [rs intForColumn:@"Height"]; member.Weight = [rs intForColumn:@"Weight"];
      member.icon = [UIImage imageWithData:[rs dataForColumn:@"Photo"]];
     NSLog(@"member.name =============  %@",member.name);
     [array addObject:member];</span> 
    } 
     [membersDB close];<span style="color:#FF0000;"> 
     NSLog(@"array[0] == %@,\narray[1] == %@,\narray[2]==%@",[array[0] name],[array[1] name],[array[2] name]);</span>
     return [array copy];
 }

</span>

打印信息如下:

在while循环中打印是正确的,不重复的,可以循环结束在打印我们添加成员的数组,发现都是重复的,也就是都是同一个对象!!!!
泪奔啊。。。。。。这时对类的理解不深刻啊,我在循环外加的 Member *member = [[Member alloc]init];初始化,也就是说再循环中我一直在对同一个对象进行重复操作,
,以至于添加成员的数组都是同一个对象,不同的个数而已。
所以解决办法应该是在循环中初始化,这样一来,每次循环都是一个新的对象(内存地址),这样一来就正确了!!!

-(NSArray *)getdataFromDatabase
{
    NSString *path = [self getDBPath];
    NSLog(@"path ==== %@",path);
    NSLog(@"self.getDBPath == %@",[self getDBPath]);
    
    FMDatabase *membersDB = [FMDatabase databaseWithPath:path];
    if (![membersDB open]) {
        NSLog(@"Failed to open membersDB");
        return nil;
        [membersDB close];
    }
    NSMutableArray *array = [NSMutableArray array];
    FMResultSet *rs = [membersDB executeQuery:@"SELECT * FROM Member"];//这里数组为空  容易出错
    


    while ([rs next])
    {<pre name="code" class="objc">     <span style="color:#FF0000;">Member *member = [[Member alloc]init];</span>

      member.name = [rs stringForColumn:@"Name"]; 
      member.age = [rs intForColumn:@"Age"]; 
      member.sex = [rs intForColumn:@"Sex"];
      member.height = [rs intForColumn:@"Height"]; member.Weight = [rs intForColumn:@"Weight"];
      member.icon = [UIImage imageWithData:[rs dataForColumn:@"Photo"]];
      NSLog(@"member.name =============  %@",member.name);
     [array addObject:member];</span> 
    } 
     [membersDB close];<span style="color:#FF0000;"> 
     NSLog(@"array[0] == %@,\narray[1] == %@,\narray[2]==%@",[array[0] name],[array[1] name],[array[2] name]);</span>
     return [array copy];
 }

 <pre name="code" class="objc"><pre name="code" class="objc"> <span style="color:#FF0000;"></span>