我正在尝试使用本文中描述的类别: http://iphonedevelopment.blogspot.com/2008/10/shuffling-arrays.html
我已设置以下内容:
// NSArray+Shuffle.h
#import <Foundation/Foundation.h>
@interface NSArray (Shuffle)
-(NSArray *)shuffledArray;
@end
// NSArray+Shuffle.m
#import "NSArray+Shuffle.h"
@implementation NSArray (Shuffle)
-(NSArray *)shuffledArray
{
NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]];
NSMutableArray *copy = [self mutableCopy];
while ([copy count] > 0)
{
int index = arc4random() % [copy count];
id objectToMove = [copy objectAtIndex:index];
[array addObject:objectToMove];
[copy removeObjectAtIndex:index];
}
// Using IOS 5 ARC
// [copy release];
return array;
}
@end
然后在我想要使用它的代码中,我导入了Category:
#import "NSArray+Shuffle.h"
然后,我试图像这样使用它:
NSArray *orderedGallary = [[NSArray alloc] initWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
@"Pic1", @"pageName",
[UIImage imageNamed:@"Pic1.jpg"],@"pageImage",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"Pic2", @"pageName",
[UIImage imageNamed:@"Pic2.jpg"],@"pageImage",
nil],
nil];
NSArray *shuffler = [[NSArray alloc] shuffledArray:orderedGallary];
_pageData = [shuffler shuffledArray:orderedGallary];
但是,我收到以下编译器错误消息:
ModelController.m: error: Automatic Reference Counting Issue: Receiver type 'NSArray' for instance message does not declare a method with selector 'shuffledArray:'
有什么想法吗?
答案 0 :(得分:2)
shuffledArray
是一个不带参数的方法,它与shuffledArray:
不同,后者是一个接受一个参数的方法。
看起来你的意思是:
NSArray* shuffled = [orderedGallery shuffledArray];
在这里,您将此消息发送到原始数组,并返回一个洗牌的新数组。
答案 1 :(得分:1)
您已声明(在.h中)并定义(在.m中)名为shuffledArray
的方法。
您正在调用名为shuffledArray:
的方法(注意冒号,表示参数)。
您想要致电
NSArray *shuffled = [orderedGallery shuffledArray];
您不需要参数,因为您将方法发送到有序数组。
(没有任何对象实际上是一个“shuffler” - 独立于数组 - 所以我不会使用该名称作为变量名。数组正在洗牌自己的副本并返回新的洗牌阵列。)
答案 2 :(得分:1)
你太努力了。您只需将-shuffledArray
发送至orderedGallery
。
NSArray *orderedGallary = [[NSArray alloc] initWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
@"Pic1", @"pageName",
[UIImage imageNamed:@"Pic1.jpg"],@"pageImage",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"Pic2", @"pageName",
[UIImage imageNamed:@"Pic2.jpg"],@"pageImage",
nil],
nil];
_pageData = [orderedGallery shuffledArray];
看看你如何声明shuffledArray
不接受任何争论?只需将此消息发送到NSArray
的任何实例,都会返回您的随机数组。
答案 3 :(得分:1)
shuffledArray不接受参数,但直接在数组上调用:
NSArray *myShuffledArray = [orderedGallery shuffledArray]