使用线程ios从另一个类调用方法

时间:2013-01-28 08:42:42

标签: iphone objective-c ios5 nsthread

我有两个类,一个是Sample类和ServerConnection类。

sample.m

.
.
    ServerConnection *serverConnection = [[ServerConnection alloc]init:val1 _handler:serverConnectionHandler _connectionURL:url];
//    [NSThread detachNewThreadSelector:@selector(run) toTarget:serverConnection withObject:NULL];    
    [serverConnection performSelectorInBackground:@selector(run) withObject:NULL];

在serverConnection中,我只有两种方法 ServerConnection.h

@interface ServerConnection : NSObject
{
//    NSString* url;
//    Handler* handler;
//    int action_code;
}

@property (nonatomic,retain) NSString* url;
@property (nonatomic,retain) Handler* handler;
@property (nonatomic,retain) NSNumber* action_code;

-(id) init:(int)_action_code _handler:(Handler *)_handler _connectionURL:(NSString *)_connectionURL;
-(void)run;

ServerConnection.m

- (id) init:(int)_action_code _handler:(Handler *)_handler _connectionURL:(NSString *)_connectionURL{
    if (self = [super init]) {
        action_code = 0;
        action_code = [[NSNumber alloc]initWithInt:_action_code];
        handler = [[Handler alloc]init:_handler];
        url = [[NSString alloc]initWithString:_connectionURL];
    }
    return self;
}

-(void)run
{
     NSLog(@"url--> %@",url);

   //Here using NSURLConnection to fetch data from server
}

当运行方法启动时,我会收到此错误,有时过多的错误访问,并在启用zombie后显示此错误消息 - [CFString release]:发送到解除分配的实例0xf9978d0的消息 * 和  对象0x11039420的 ** malloc: 错误:未分配被释放的指针 在malloc_error_break中设置断点以进行调试**

我推荐旧帖并尝试解决但仍然面临同样的问题。有人请指出我在哪里做错了吗?

1 个答案:

答案 0 :(得分:1)

我的url ivar没有看到任何错误。这是你的整个代码吗?什么是ServerConnection生命周期?星期一早上可能是我没有看到任何可疑的原因......几乎没有其他评论...

action_code = 0;行没用,因为您在下一行分配了NSNumberaction_codeNSNumber,因此,即使您要为其指定0,也应该写action_code = @( 0 )

另外,样式... action_code应命名为actionCodeinit...方法应如下所示:

- (id)initWithActionCode:(int)actionCode handler:(Handler *)handler connectionURL:(NSString *) connectionURL {

if (self = [super init]) {应该看起来像if ( ( self = [super init] ) ) {或使用两个班轮:

self = [super init];
if ( self ) {

您应该改进自己的风格,让其他人更容易理解您的代码。

相关问题