0

Help me in adding objects in array of app delegate from UIViewController in Objective-C I guess I am doing mistake, help me in this regard

I want to add objects in array of app delegate from view controller

in appdelegate.h

@property (nonatomic, retain) NSMutableArray *sharedArray;

in appdelegate.m

@implementation AppDelegate
@synthesize sharedArray;

inside didfinishlaunching

self.sharedArray = [[NSMutableArray alloc] init];

in ViewController

@interface ViewController () {

    UIApplication *appDelegate;


Inside viewdidload of viewcontroller

appDelegate = [[UIApplication sharedApplication] delegate];
[appdelegate.sharedArray addObject:array];
9
  • can you explain what you want to do? Commented Apr 11, 2018 at 10:56
  • What is your problem here? Anyway, you don't need to declare appDelegate in ViewController Commented Apr 11, 2018 at 10:57
  • I want to add objects in array of app delegate from view controller Commented Apr 11, 2018 at 10:57
  • @iOSDeveloper check Anbu's answer. Commented Apr 11, 2018 at 10:59
  • 1
    import AppDelegate where you want to use that Commented Apr 11, 2018 at 11:13

2 Answers 2

2

Your code is fine and correct, but you need to initialize the memory of your array before append the object

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    self. sharedArray = [NSMutableArray array];

    return YES;
}

finally call the method as

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
 [appDelegate.sharedArray addObject:array];

finally import the header

#import "AppDelegate.h"
Sign up to request clarification or add additional context in comments.

3 Comments

I have added self.sharedArray = [[NSMutableArray alloc] init];
@RealmOfFire- sure bro, it works, we need the conformation from questioner
@Anbu.karthik upvoted your answer, but I forgot to import the app delegate
1

Change declaration of

UIApplication *appDelegate;

to

AppDelegate *appDelegate;

//

self.appDelegate =  (AppDelegate *)[[UIApplication sharedApplication] delegate];

// on top you should

#import "AppDelegate.h"

2 Comments

Unknown type name 'AppDelegate' it gives this error when doing this
Happy coding ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.