iOS newb trying to pull an array from another class and a getting error. Fundamentally, I don't really understand the difference between methods and properties, I realize, so this might help me get a better understanding of that.
I have created a method that returns an array. I want to use that array in the other class (like a function returning a value in other languages) so I thought I would do it as follows:
class1
- (id) getTags{
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Tags"];
fetchRequest.resultType = NSDictionaryResultType;
NSError *error = nil;
NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest
error:&error];
NSMutableArray * tags = [[results valueForKey:@"tag"] mutableCopy];
return tags;
}
In other words, I want to use what that method returns as a sort of variable which in Objective C is called properties. The method is also in the .h file so that it is public.
In class 2 I import class 1 at top and then try to call method as follows:
NSArray *newarray = [class1 getTags];
However I get error "No known class method for selector getTags"
Can anyone tell me what I am doing wrong?
Thanks.
I suspect this line;
NSArray *newarray = [class1 getTags];
Actually, you should use class instance, not class itself. To use this kind of function call, you should declare getTags as class level function(+ function), not - function
So your code should be look like this;
class1 *class1Instance = [[class1 alloc] init];
NSArray *newarray = [class1Instance getTags];
The problem is the code NSArray *newarray = [class1 getTags];
You are calling class method getTags
in class1
; however you only have an instance method called getTags
in class1
.
To solve it, change the - to + in the method signature, which will change your method from an instance method to a class method. (In java terms: + is where you put a static in the method).
However, there are quite a lot of style issues in your code. First, I don't think putting code in .h is a good practice. What you might want is
.h
@interface Class1
+ (NSArray *)getTags;
@end
.m
@implementation Class1
+ (NSArray *)getTags { ... }
@end
so you declare your public interface in .h file and implementation in .m. Also, you probably want to capitalize your class name.
You shouldn't use id
as a return type and assign that id
from [class1 getTags]
to NSArray *
. There is a implicit cast there, which sometimes could lead to some good debug time.
NSArray
CAN be used as return type of your method because NSMutableArray
is inherited from NSArray
- Apple Documentation of NSMutableArray
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.