I am new to objective c. I have an mainViewController class and i created another object class. I am declaring the other class inside the .h file of the mainViewController. I use
#import <Foundation/Foundation.h>
#import "OtherClass.h"
NS_ASSUME_NONNULL_BEGIN
@interface ViewController : UIViewController
@property (strong, nonatomic) OtherClass *jsonData;
@end
NS_ASSUME_NONNULL_END
Then i call a function of the Other Class from the mainViewController .m file.
The method returns NSMutableArray and it works. But there is a possibility an error might occur so it might not return the NSMutableArray but an NSError. I need the class to return the error to the mainViewController.
How can i achieve this? Any help appreciated.
CodePudding user response:
You can use: id jsonData instead of OtherClass *jsonData:
@property (strong, nonatomic) OtherClass *jsonData;
=>
@property (strong, nonatomic) id jsonData;
And then do
if ([jsonData isKindOfClass: [OtherClass class]])
{
}
else if ([jsonData isKindOfClass: [NSError class]])
{
}
else
{
//It's none
}
But maybe you want to have 2 properties, might be simpler to use with just if (jsonData) {} or if (jsonError) {}?
@property (strong, nonatomic) OtherClass *jsonData;
@property (strong, nonatomic) NSError *jsonError;
Another possibility would be to embed that into a custom object:
@interface ResponseData: NSObject
@property (strong, nonatomic) OtherClass *data;
@property (strong, nonatomic) NSError *error;
@end
And then:
@interface ViewController : UIViewController
@property (strong, nonatomic) ResponseData *json;
@end
And check json.data or json.error?
CodePudding user response:
My Objective-C is a little rusty, but I believe I can help.
id in ObjC is quite similar to AnyObject in Swift.
So your type could use id but then you would need to cast it
You could us the isKindOfClass to test which type is returned and then cast it.
@property (strong, nonatomic) id *someType;
if [someType isKindOfClass:[NSMutableArray class]) {
}
if [someType isKindOfClass:[NSError class]) {
}
