NSArray:添加多个具有相同值的对象

发布于 2024-09-03 02:38:36 字数 86 浏览 2 评论 0 原文

如何将多个对象添加到我的 NSArray 中?每个对象都将具有相同的值。

前任。

我希望将值“SO”添加到我的数组中 10 次

How can I add multiple objects to my NSArray? Each object will have the same value.

Ex.

I want the value "SO" added to my array 10 times

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

不忘初心 2024-09-10 02:38:36

您可以使用一组对象初始化数组:

NSString * blah = @"SO";
NSArray * items = [NSArray arrayWithObjects: blah, blah, nil];

或者您可以使用可变数组并稍后添加对象:

NSMutableArray * mutableItems = [[NSMutableArray new] autorelease];
for (int i = 0; i < 10; i++)
    [mutableItems addObject:blah];

You can initialize the array with a set of objects:

NSString * blah = @"SO";
NSArray * items = [NSArray arrayWithObjects: blah, blah, nil];

or you can use a mutable array and add the objects later:

NSMutableArray * mutableItems = [[NSMutableArray new] autorelease];
for (int i = 0; i < 10; i++)
    [mutableItems addObject:blah];
北城孤痞 2024-09-10 02:38:36

如果您不想使用可变数组,也不想重复标识符 N 次,请利用可以从 C 样式数组初始化的 NSArray

@interface NSArray (Foo) 
+ (NSArray*)arrayByRepeatingObject:(id)obj times:(NSUInteger)t;
@end

@implementation NSArray (Foo)
+ (NSArray*)arrayByRepeatingObject:(id)obj times:(NSUInteger)t {
    id arr[t];
    for(NSUInteger i=0; i<t; ++i) 
        arr[i] = obj;
    return [NSArray arrayWithObjects:arr count:t];    
}
@end

// ...
NSLog(@"%@", [NSArray arrayByRepeatingObject:@"SO" times:10]);

If you don't want to use mutable arrays and also don't want to repeat your identifier N times, utilize that NSArray can be initialized from a C-style array:

@interface NSArray (Foo) 
+ (NSArray*)arrayByRepeatingObject:(id)obj times:(NSUInteger)t;
@end

@implementation NSArray (Foo)
+ (NSArray*)arrayByRepeatingObject:(id)obj times:(NSUInteger)t {
    id arr[t];
    for(NSUInteger i=0; i<t; ++i) 
        arr[i] = obj;
    return [NSArray arrayWithObjects:arr count:t];    
}
@end

// ...
NSLog(@"%@", [NSArray arrayByRepeatingObject:@"SO" times:10]);
若能看破又如何 2024-09-10 02:38:36

我的 2:

NSMutableArray * items = [NSMutableArray new];
while ([items count] < count)
    [items addObject: object];

My ¢2:

NSMutableArray * items = [NSMutableArray new];
while ([items count] < count)
    [items addObject: object];
噩梦成真你也成魔 2024-09-10 02:38:36

只需使用 initWithObjects: (或您喜欢的任何方法)。 NSArray 不要求其对象是唯一的,因此您可以多次添加相同的对象(或相等的对象)。

Just add them with initWithObjects: (or whichever method you prefer). An NSArray does not require its objects to be unique, so you can add the same object (or equal objects) multiple times.

↘紸啶 2024-09-10 02:38:36

现在,您可以使用数组文字语法。

NSArray *items = @[@"SO", @"SO", @"SO", @"SO", @"SO"];

您可以像 items[ 0];

Now, you can use array literal syntax.

NSArray *items = @[@"SO", @"SO", @"SO", @"SO", @"SO"];

You can access each element like items[0];

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文