ramonthegreat ramonthegreat -4 years ago 171
Objective-C Question

IOS Share Extension NSMutableArray addObject Unrecognized selector sent to instance

After clicking post to the share dialog, the Host App(e.g. Safari) hangs up if arrSites variable is currently not empty. I can only store 1 object inside my arrSites variable. How can I addObject to my NSMutableArray variable?

Below is my implemented code and it generates an error in [arrSites addObject:dictSite] line.

- (void)didSelectPost
{
inputItem = self.extensionContext.inputItems.firstObject;

NSItemProvider *urlItemProvider = [[inputItem.userInfo valueForKey:NSExtensionItemAttachmentsKey] objectAtIndex:0];

if ([urlItemProvider hasItemConformingToTypeIdentifier:(__bridge NSString *)kUTTypeURL])
{
NSLog(@"++++++++++ Attachment is a URL");
[urlItemProvider loadItemForTypeIdentifier:(__bridge NSString *)kUTTypeURL options:nil completionHandler:^(NSURL *url, NSError *error)
{
if (error)
{
NSLog(@"Error occured");
}
else
{
NSMutableArray *arrSites;
if ([sharedUserDefaults valueForKey:@"SharedExtension"]){
arrSites = [sharedUserDefaults objectForKey:@"SharedExtension"];
}else{
arrSites = [[NSMutableArray alloc] init];
}

NSDictionary *dictSite = [NSDictionary dictionaryWithObjectsAndKeys:self.contentText, @"Text", url.absoluteString, @"URL",nil];

[arrSites addObject:dictSite];
[sharedUserDefaults setObject:arrSites forKey:@"SharedExtension"];
[sharedUserDefaults synchronize];

UIAlertController * alert= [UIAlertController
alertControllerWithTitle:@"Success"
message:@"V7 Posted Successfully."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction
actionWithTitle:@"OK"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[UIView animateWithDuration:0.20 animations:^
{
self.view.transform = CGAffineTransformMakeTranslation(0, self.view.frame.size.height);
}
completion:^(BOOL finished)
{
[self.extensionContext completeRequestReturningItems:nil completionHandler:nil];
}];
}];

[alert addAction:ok];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
}

Answer Source

Without memory allocation you can't add the object to array, use like

// allocate the memory of array in before 
NSMutableArray *arrSites = [[NSMutableArray alloc] init];
if ([sharedUserDefaults valueForKey:@"SharedExtension"]){
    [arrSites addObjectsFromArray:[sharedUserDefaults objectForKey:@"SharedExtension"]];
}
[arrSites addObject:dictSite];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download