5

4つのオブジェクトで使用されるスコアを含むNSMutablearrayである@propertyがあるとします。これらはゼロとして初期化され、viewDidLoad中およびアプリの操作中に更新されます。

どういうわけか、特に宣言と初期化のステップで、何をする必要があるかについて頭を悩ませることはできません。

私はこれが私有財産である可能性があると信じています。

@property (strong, nonatomic) NSMutableArray *scores;

@synthesize scores = _scores;

次に、viewDidLoadでこのようなことを試みますが、エラーが発生します。構文の助けが必要だと思います。または、非常に基本的なものが欠けています。

self.scores = [[NSMutableArray alloc] initWithObjects:@0,@0,@0,@0,nil];

それを初期化する適切な方法ですか?次に、(NSNumber *)updateValueをたとえばn番目の値に追加するにはどうすればよいですか?

編集:私はそれを理解したと思います。

-(void)updateScoreForBase:(int)baseIndex byIncrement:(int)scoreAdjustmentAmount
{
    int previousValue = [[self.scores objectAtIndex:baseIndex] intValue];
    int updatedValue = previousValue + scoreAdjustmentAmount;
    [_scores replaceObjectAtIndex:baseIndex withObject:[NSNumber numberWithInt:updatedValue]];
}

これを行うためのより良い方法はありますか?

4

1 に答える 1

5

で初期化してviewDidLoadいますが、 で行う必要がありますinit

これらは両方とも似ており、完全に有効です。

_scores = [[NSMutableArray alloc] initWithObjects:@0,@0,@0,@0,nil]; 

また、

self.scores=[[NSMutableArray alloc]initWithObjects:@0,@0,@0, nil];

あなたの最後の質問... あなたThen how do I add (NSNumber *)updateValue to, say, the nth value? なら、addObject:それは最後に追加されます。必要insertObject:atIndex:なインデックスを作成する必要があり、後続のすべてのオブジェクトは次のインデックスにシフトします。

 NSInteger nthValue=12;
[_scores insertObject:updateValue atIndex:nthValue];

編集:

編集後、

NSInteger previousValue = [[_scores objectAtIndex:baseIndex] integerValue];
NSInteger updatedValue = previousValue + scoreAdjustmentAmount;
[_scores replaceObjectAtIndex:baseIndex withObject:[NSNumber numberWithInt:updatedValue]];
于 2012-12-06T04:14:35.080 に答える