2011-12-07 16 views
0

好吧,我想了解这个post关于从一个视图控制器到其他数据传输的最佳方式。iphone委托协议无法保存对象

事情是,如果我想设置对象的attr它的作品像冠军。如果我尝试设置整个对象,它不会这样做。

我的代码是:

@protocol AppDelegateProtocol 

    - (Lote*) theLoteAppObject; 

@end 

上的AppDelegate:

@interface AgroferiaAppDelegate : NSObject <UIApplicationDelegate, AppDelegateProtocol> { 
Lote *theLoteAppObject; 

} 

@property (nonatomic, retain) Lote *theLoteAppObject; 

@end 
... 
... 
- (id) init; 
{ 
self.theLoteAppObject = [[Lote alloc] init]; 
[theLoteAppObject release]; 
return [super init]; 
} 

类在那里我得到这个问题(的UIViewController):

-(void)tableView:(UITableView *) aTableView didSelectRowAtIndexPath:(NSIndexPath *) indexPax{ 

... 

NSArray *lotes = [[self.evento lotesStore]allLotes] ; 

Lote* theDataObject = [self theLoteAppObject]; 

theDataObject._id = [[lotes objectAtIndex:[indexPax row]]_id]; 
[[self navigationController]pushViewController:lotesOpViewController animated:YES]; 

} 
- (Lote*) theLoteAppObject;{ 
id<AppDelegateProtocol> theDelegate = (id<AppDelegateProtocol>) [UIApplication sharedApplication].delegate; 
Lote* theDataObject; 
theDataObject = (Lote*) theDelegate.theLoteAppObject; 
return theDataObject; 
    } 

,这样的作品,但如果我想做下面的事情,

theDataObject = [lotes objectAtIndex:[indexPax row]]; 

它不保存数据对象上的对象。

这是一个糟糕的内存管理问题吗?

编辑:是它的数据对象从AppDelegate的参考?或者这是问题?

+0

我猜你阵列中的所有Lote物品都是自动释放的。检查你的'[lotes objectAtIndex:[indexPax row]];'返回的对象是否是一个有效的Lote对象,如果是,则对其进行“复制”。 –

+0

atm做objectAtIndex我可以看到对象在那里,并与他的所有信息。所以你建议我必须复制他。新问题,在这种情况下做到这一点的最佳方式? –

+0

想添加,是否可以,如果我创建一个方法initWithLote:(Lote *)copyLote在Lote类中,我做了深层复制,如果他的所有attr? –

回答

1

尝试这样:

if([indexPax row] < [lotes count]) 
{ 
    Lotes * dataObjectToCopy = [lotes objectAtIndex: [indexPax row]]; 
    if(dataObjectToCopy) 
    { 
     theDataObject = [dataObjectToCopy copy]; 
    } 
} 

这将创建一个单独的,保留你的Lote对象的副本。确保在完成后释放它(如果您不使用ARC)。

+0

ARC是[自动引用计数](http://clang.llvm.org/docs/AutomaticReferenceCounting.html)。我修改了我的原始答案,以显示更简单的代码。如果你仍然看到一个“copyWithZone”无法识别的选择器错误,那么它可能是其他的错误。 –

+0

我做了副本,但当我在代理上查找该对象时,我得到零,所以没有被设置为appDelegate:S后的DataObject._id = [[lotes objectAtIndex:[indexPax row]] _ id];我不需要做其他事情?与此同时我为appDelegate和整个应用程序设置了对象? –

+1

迈克尔,他不需要符合'NSCopying'并实现'copyWithZone:'? – jstevenco