Raz*_*iel 0 pointers objective-c parameter-passing
我有一些课:
@interface SearchBase : NSObject
{
NSString *words;
NSMutableArray *resultsTitles;
NSMutableArray *resultsUrl;
NSMutableArray *flag;
}
@property (copy, nonatomic) NSString *words;
- (id) getTitleAtIndex:(int *)index;
- (id) getUrlAtIndex:(int *)index;
- (id) getFlagAtIndex:(int *)index;
@end
@implementation SearchBase
- (id) initWithQuery:(NSString *)words
{
if (self = [super init])
{
self.words = words;
}
return self;
}
- (id) getTitleAtIndex:(int *)index
{
return [resultsTitles objectAtIndex:index];
}
- (id) getUrlAtIndex:(int *)index
{
return [resultsUrl objectAtIndex:index];
}
- (id) getFlagAtIndex:(int *)index
{
return [flag objectAtIndex:index];
}
@end
Run Code Online (Sandbox Code Playgroud)
但是当我尝试在子类中使用一些这些get-methods时,我看到:
warning: passing argument 1 of 'getTitleAtIndex:' makes pointer from integer without a cast
warning: passing argument 1 of 'getFlagAtIndex:' makes pointer from integer without a cast
warning: passing argument 1 of 'getUrlAtIndex:' makes pointer from integer without a cast
Run Code Online (Sandbox Code Playgroud)
并且程序无法正常工作.怎么了?怎么解决?
您正在将整数值传递给您的方法,这是错误的,因为您声明的函数只接受integer pointer不是值的原因,这是警告的原因.objectAtIndex:方法只接受整数值而不是指针,所以如果运行,可能会导致应用程序崩溃.
最简单的方法是更改函数中的参数类型.
- (id) getTitleAtIndex:(int )index;
- (id) getUrlAtIndex:(int )index;
- (id) getFlagAtIndex:(int )index;
Run Code Online (Sandbox Code Playgroud)
和函数实现可以类似于下面的函数.
- (id) getTitleAtIndex:(int )index
{
if(index < [resultsTitles count] )
return [resultsTitles objectAtIndex:index];
else
return nil;
}
Run Code Online (Sandbox Code Playgroud)