我得到了:
@interface ViewController : UIViewController
{
int index_counter;
//NSMutableArray *logins;
}
@property (weak, nonatomic) IBOutlet UITextField *count;
@property (strong, nonatomic) NSMutableArray *logins;
- (IBAction)next_button:(id)sender;
@end
这是一个包含对象的数组:
@interface THEOBJECT : NSObject
{
NSString *uname;
int counter;
}
-(void) SetUser: (NSString *) username;
-(void) SetCount: (int) value;
-(void) print;
@property (nonatomic, retain) NSString *uname;
@property (nonatomic,readwrite) int counter; //not sure if this is correct
@end
@implementation SiteValue
@synthesize uname;
@synthesize counter;
-(void) SetCount:(int) value
{
counter=counter+1;
}
@end
我的方法应该在数组的每个索引中增加对象THEOBJECT中的计数值:
- (IBAction)next_button:(id)sender
{
index_counter=index_counter-1;
if (index_counter<0)
{
index_counter=0;
}
username.text=[[logins objectAtIndex:index_counter] uname];
[[logins objectAtIndex:index_counter] counter]=[[logins objectAtIndex:index_counter] counter]+1; //ERROR HERE.
}
在我写“ERROR HERE”的地方,每当我按下 next 按钮并在数组中存储+1时,它应该递增计数值。 但它给我一个只读错误。确切的错误是"assigning to 'readonly' return result of an Objective-C message not allowed"
。我认为最好的办法是调用setcount:
方法,但它不会让我调用它,因为它是两个不同的接口。有什么想法吗?
答案 0 :(得分:1)
counter
是一种访问方法:
[[logins objectAtIndex:index_counter] counter]
它会向您返回一个值,因此它不是您可以设置的内容(它就像说50 = 100
- 您无法设置这样的值)。
如果要设置变量,则需要使用setCounter
方法:
[[logins objectAtIndex:index_counter] setCounter:[[logins objectAtIndex:index_counter] counter]+1];
答案 1 :(得分:1)
在行中:
[[logins objectAtIndex:index_counter] counter]=[[logins objectAtIndex:index_counter] counter]+1; //ERROR HERE.
您应该使用setter而不是分配左侧属性counter
的getter。所以你应该将该行改为:
[[logins objectAtIndex:index_counter] setCounter:[[logins objectAtIndex:index_counter] counter]+1];
为了更清楚,您可以将该行分为两行:
int currentValue = [[logins objectAtIndex:index_counter] counter];
[[logins objectAtIndex:index_counter] setCounter:currentValue+1];
您也可以使用点符号并将其写为:
THEOBJECT *myObject = [logins objectAtIndex:index_counter];
int currentValue = myObject.counter;
myObject.counter = currentValue + 1;
或者:
THEOBJECT *myObject = [logins objectAtIndex:index_counter];
myObject.counter = myObject.counter + 1;
或者:
THEOBJECT *myObject = [logins objectAtIndex:index_counter];
myObject.counter++;
答案 2 :(得分:1)
最简单的方法是访问属性counter
,但为了做到这一点,您需要在objectAtIndex:
返回id
时转换结果,而Objective-C允许你可以在id
实例上调用任何不能调用任何属性的方法:
((THEOBJECT *)[logins objectAtIndex:index_counter]).counter++;