簡體   English   中英

NSMutableArray中的對象無法訪問Objective-C

[英]Objects in NSMutableArray inaccesible Objective-C

//在Xcode 4.2中打開了ARC

創建了一個靜態函數,該函數執行查詢並從數據庫SQLite獲取值。 函數displayquery返回的數組值是一個包含記錄的可變數組的數組。 我想將其轉換為客戶端對象,並將列表列表存儲在NSMutable對象中,然后再返回它。

靜態功能

+ (NSMutableArray*) list
{

    NSString *querySQL = //some query;

    NSMutableArray *values = [Client displayQuery:querySQL numberOfColumns:7];

    NSMutableArray *lst = nil;

    if (values != nil)
    {
        lst = [NSMutableArray arrayWithObject:@"Client"];

        for (int i = 0; i<[[values objectAtIndex:0] count] ; i++) 
        {    
            [lst addObject:[Client new ]];
        }
        for (int i = 0; i<[[values objectAtIndex:0] count] ; i++) 
        {    

            Client *aClient = [lst objectAtIndex:i];
            //error occurs during the execution of this line.
            //all properties of Class client are (retain,nonatomic)
            aClient.idClient = [[values objectAtIndex:0]objectAtIndex:i];
            aClient.prenom = [[values objectAtIndex:1]objectAtIndex:i];
            aClient.name = [[values objectAtIndex:2]objectAtIndex:i];
            aClient.address = [[values objectAtIndex:3]objectAtIndex:i];
            aClient.telephone = [[values objectAtIndex:4]objectAtIndex:i];
            aClient.email = [[values objectAtIndex:5]objectAtIndex:i];
            aClient.weight = [[values objectAtIndex:6]objectAtIndex:i];
            [lst addObject: aClient];

        }
    }
    return lst;
}

問題在於, lst數組中的第一個元素是NSString ,它不具有Client類所具有的任何屬性,並且當您嘗試分配給它時,會出現錯誤。 您的代碼中存在一些問題:

  1. 不要在數組中添加@"Client"作為元素,因為它似乎不屬於該元素。
  2. 您無需將“ Client對象“預添加”到陣列。 只需創建它們,然后將它們添加到陣列即可。
  3. 當您擁有數組的數組時,查找項目時可能會更難理解每個索引的含義。 我在您的代碼中重命名了幾個變量,因為它使我更容易理解。

我認為您的代碼應更像這樣:

+ (NSMutableArray*) list
{
    NSString *querySQL = //some query;
    NSMutableArray *columns = [Client displayQuery:querySQL numberOfColumns:7];
    NSMutableArray *lst = nil;

    if (columns == nil)
        return nil;

    NSUInteger count = [[columns objectAtIndex:0] count];
    lst = [NSMutableArray arrayWithCapacity:count];

    for (NSUInteger row = 0; row < count; row++) 
    {    
        Client *aClient = [Client new];

        aClient.idClient = [[columns objectAtIndex:0] objectAtIndex:row];
        aClient.prenom = [[columns objectAtIndex:1] objectAtIndex:row];
        aClient.name = [[columns objectAtIndex:2] objectAtIndex:row];
        aClient.address = [[columns objectAtIndex:3] objectAtIndex:row];
        aClient.telephone = [[columns objectAtIndex:4] objectAtIndex:row];
        aClient.email = [[columns objectAtIndex:5] objectAtIndex:row];
        aClient.weight = [[columns objectAtIndex:6] objectAtIndex:row];

        [lst addObject: aClient];
    }

    return lst;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM