2012-10-10 53 views
3

我想訪問塊中的實例變量,但始終在塊中接收EXC_BAC_ACCESS。在我的項目中不使用ARC。如何訪問塊中的實例變量

.h file 

@interface ViewController : UIViewController{ 
    int age; // an instance variable 
} 



.m file 

typedef void(^MyBlock) (void); 

MyBlock bb; 

@interface ViewController() 

- (void)foo; 

@end 

@implementation ViewController 

- (void)viewDidLoad{ 
    [super viewDidLoad]; 

    __block ViewController *aa = self; 

    bb = ^{ 
     NSLog(@"%d", aa->age);// EXC_BAD_ACCESS here 
     // NSLog(@"%d", age); // I also tried this code, didn't work 
    }; 

    Block_copy(bb); 

    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    btn.frame = CGRectMake(10, 10, 200, 200); 
    [btn setTitle:@"Tap Me" forState:UIControlStateNormal]; 
    [self.view addSubview:btn]; 

    [btn addTarget:self action:@selector(foo) forControlEvents:UIControlEventTouchUpInside]; 
} 

- (void)foo{ 
    bb(); 
} 

@end 

我不熟悉塊編程,我的代碼中有什麼問題?

+0

請張貼您的年齡申報 – danh

回答

1

您正在訪問在堆棧中分配的塊不在範圍內。您需要將bb分配給複製的塊。 bb也應該移動到類的實例變量。

//Do not forget to Block_release and nil bb on viewDidUnload 
bb = Block_copy(bb); 
+0

如果這是你的完整類,那麼你還需要在'dealloc'方法中使用Block_release'bb'。 – Joe

+0

謝謝。這只是一個演示。我知道這個問題。我發現一個奇怪的語法:如果像這樣定義bb,'@property(nonatomic,copy)BB bb; '然後我可以使用'self.bb();'在'foo()'方法中調用它。 – tristan

0

你應該定義你的age伊娃正確的存取方法:

@implementation ViewController 
@synthesize age; 
... 

,並使用它像這樣:

NSLog(@"%d", aa.age);// EXC_BAD_ACCESS here 

如果

@interface ViewController : UIViewController{ 
    int age; // an instance variable 
} 
@property (nonatomic) int age; 
... 
在.m文件

您可以正確分配ViewController,以便在塊執行前不會釋放其實例特德,這將解決它。

+1

如果age的目的是爲私人,則不需要屬性。 – Joe