2014-01-23 27 views
0

我想知道UIScrollView中的實例。UIScrollView中的實例

我通過編寫簡單的代碼檢查了UIScrollView中的實例發生了什麼。

這是代碼。


UIViewController.m

#import "ViewController.h" 
#import "CustomScrollView.h" 


@interface ViewController() 

@end 

CustomScrollView *sv1, *sv2; 

@implementation ViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    int height = self.view.frame.size.height; 

    sv1 = (CustomScrollView*)[[CustomScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, height/2)]; 
    sv1.backgroundColor = [UIColor redColor]; 
    [self.view addSubview:sv1]; 
    [sv1 setIntegerWithNum:1]; 

    sv2 = (CustomScrollView*)[[CustomScrollView alloc] initWithFrame:CGRectMake(0, height/2, 320, height/2)]; 
    sv2.backgroundColor = [UIColor blueColor]; 
    [self.view addSubview:sv2]; 
    [sv2 setIntegerWithNum:2]; 

    int returnVal1 = [sv1 getInteger]; 
    int returnVal2 = [sv2 getInteger]; 

    NSLog(@"Sv1:%d, Sv2:%d", returnVal1, returnVal2); 
} 

CustomScrollView.m

#import "CustomScrollView.h" 

int number; 
@implementation CustomScrollView 

-(void)setIntegerWithNum:(int)num { 
    number = num; 
} 
-(int)getInteger { 
    return number; 
} 

這裏,我看到在輸出區域的值。 我以爲它會是「Sv1:1,Sv2:2」,因爲數字分別設置爲1和2。 但我得到了像「Sv1:2,Sv2:2」的輸出

這裏發生了什麼?

+1

集'number'在'CustomScrollView.h' @property – Akhilrajtr

回答

0

你只有一個你CustomScrollView.h您的設置int類型的變量,你的二傳手setIntegerWithNum,然後你與你的getter getInteger返回的「int數」的值。基本上用你的setter,你設置你的「數字」變量兩次。第二次設置爲2.所以變量number然後保存2,覆蓋以前的值1.

因此,當您使用NSLog的getter時,您將返回兩次相同的值。

我會按照@ Akhilrajtr的建議。只需將號碼設置爲int類型的屬性即可。然後你將正確地返回每個對象的屬性。也就是說,每個單獨的對象int屬性爲sv1和sv2。

您可以@property (nonatomic, assign) NSInteger *number;

0

做到這一點試試這個,

設置numberCustomScrollView.h @property通過

@property(nonatomic, assign) int number; 

然後在ViewController

sv1 = (CustomScrollView*)[[CustomScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, height/2)]; 
sv1.backgroundColor = [UIColor redColor]; 
[self.view addSubview:sv1]; 
[sv1 setNumber:1]; 

sv2 = (CustomScrollView*)[[CustomScrollView alloc] initWithFrame:CGRectMake(0, height/2, 320, height/2)]; 
sv2.backgroundColor = [UIColor blueColor]; 
[self.view addSubview:sv2]; 
[sv2 setNumber:2]; 

int returnVal1 = [sv1 number]; 
int returnVal2 = [sv2 number]; 

NSLog(@"Sv1:%d, Sv2:%d", returnVal1, returnVal2); 
0

這是因爲你宣佈

int number; 

不作爲實例變量或屬性。 您可以通過兩種方式

做到這一點

1.

@interface CustomScrollView(){ 
int number; 
} 
@end 

2.

@interface CustomScrollView() 
@property(nonatomic)int number; 

@end