【问题标题】:Objective-C: No objects in array after adding them. Out of scope!Objective-C:添加后数组中没有对象。超出范围!
【发布时间】:2011-11-18 11:21:21
【问题描述】:

我在一个对象中有一个 NSMutableArray。 在对象方法中,我会这样做:

/* ... */
[[LRResty client] get:connectURL withBlock:^(LRRestyResponse *r) {
    SBJsonParser *jsonParser = [SBJsonParser new];
    NSDictionary *jsonResponse = [jsonParser objectWithString:[r asString]];
    NSDictionary *permittedBases= [jsonResponse objectForKey:@"permittedBases"];
    Database *database = [[Database alloc] init];

    for (id key in permittedBases) {
        /* ... */
        [workingDatabases addObject:database];
    }
}];

return workingDatabases;    

在返回行,我的数组中没有对象(不再)。我知道“数据库”对象超出范围这一事实。但我将它们保存在数组中。

我在监督什么吗?

如果有帮助,这里是头文件:

@class Database;

@interface CommunicationHelper : NSObject {
    NSMutableArray *workingDatabases;
}


// The function where the problem appears:
- (NSMutableArray *)getDatabasesForWebsite:(Website *)websiteIn; 

@property(nonatomic,copy) NSMutableArray *workingDatabases;


@end

【问题讨论】:

    标签: objective-c arrays scope


    【解决方案1】:

    在使用该数组之前,只需在某处分配您的工作数据库(可变数组)。

    一旦你分配它,它就会正常工作。

    【讨论】:

    • 这不是问题。我在init方法中分配的。
    • @MarcBackes 实际上,这与我在处理可变数组时遇到的问题相同。我还在我的 viewDidLoad 函数中分配了可变数组,但我仍然得到超出范围的东西。所以我做了什么,我在同一个函数中分配了数组,并在它的工作结束时释放它。只需尝试在使用它的同一函数中分配可变数组,或者在“init”中分配它,将其加载到 viewDidLoad 中。试一试。:)
    【解决方案2】:

    我认为这是因为 [LRResty client] get: 是异步的。该块在连接完成时被调用,即在调用返回之后。

    //Called first
    [[LRResty client] get:connectURL
    
    //Called second
    return workingDatabases;
    
    //Called later when the connection is finished
    SBJsonParser *jsonParser = [SBJsonParser new];
        NSDictionary *jsonResponse = [jsonParser objectWithString:[r asString]];
        NSDictionary *permittedBases= [jsonResponse objectForKey:@"permittedBases"];
        Database *database = [[Database alloc] init];
    
        for (id key in permittedBases) {
            /* ... */
            [workingDatabases addObject:database];
        }
    

    编辑

    Ajeet 也有一个有效点,请确保您的数组已初始化。

    【讨论】:

      【解决方案3】:

      我使用 LRResty 框架来访问 RESTful Web 服务。无论如何,这是一件奇怪的事情,所以我转向了一个功能更丰富的框架,称为“ASIHTTP”。我会向任何想在 iOS 上使用 RESTful 服务(以及更多)的人推荐它

      【讨论】:

        猜你喜欢
        • 2016-11-12
        • 1970-01-01
        • 1970-01-01
        • 2012-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多