How to use one array in different classes? - ios

I have an array. It is filled in one class named "SampleDataDAO".
What i need:
In the 2nd class named "MainMenu" i need to keep this code:
- (void)viewDidLoad
{
[super viewDidLoad];
daoDS = [[SampleDataDAO alloc] init];
self.ds = daoDS.PopulateDataSource;
}
And in the third class named "HView" i need to use array "ds" (NSMutableArray).
But i need to use it already filled from 2nd class, to return the count of elements:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return ds.count;
}
Thanks for helping!

Why should not you have a singleton class, and have that array as a member of that singleton class.
More info on singleton found here

Rather than using singletons, or getting a reference to the array from your appDelegate (which is just the same as using a singleton). A better way would be to pass the array as a reference to the view controller when you create it.
This is similar to the way that you pass a managed object context to view controllers if you are using Core Data, rather than calling down to the app delegate to get it.

Why don't u try to use constant file for this type or requirement.
Use these files for your requirement.
Constant.h
Constant.m
Import Constant.h file in your viewController and use that methods to set and get array directly with class name as
NSArray *array=[Constant getArray];
Or
[Constant setArray:array];

Related

Sharing data between two table views

I have two table views that contain a mutable array of objects that can be instantiated by the user with various properties. The class and its properties are within separate .h and .m files that the table views access.
I would like the two table views to look identical so that when a user adds, deletes, or moves an object in one table view, the second table view is immediately updated. I understand that they will be sharing a mutable array, but I'm not sure where to put it so that changes in one table view occurs in the other table view.
Additionally, is this a situation in which I would make one of the table views a subclass of the other?
Suppose there is a controller owns the NSMutableArray object and the two table views.
Use the KVO feature, let the two table view retain (use strong as property) the NSMutableArray object.
Create a new delegates array property like NSArray< id<MyArrayNotifier> > *delegates for the NSMutableArray object's owner, implement the MyArrayNotifier protocol in two table view classes, add the table objects to delegates array. Now you could get notified when your focused message arrived.
First you should make a singleton class that contains that mutable array so you can edit/access it anywhere , whenever you update that array reload the visible tableView , if the other tableView is also visible reload it(either with delegate , observer , notificationCenter), otherwise it will be updated with the last edit when you open the VC that contains it , also you can make a use of viewDidAppear to reload the table inside it as another choice instead of delegates if it's the logic of your app
// .h
#import <Foundation/Foundation.h>
#interface GlobalData : NSObject
#property(nonatomic,retain)NSMutableArray*masterArray;
+(GlobalData*)shared;
#end
// .m
#import "GlobalData.h"
#implementation GlobalData
static GlobalData *instance = nil;
+(GlobalData *)shared
{
#synchronized(self)
{
if(instance==nil)
{
instance = [GlobalData new];
instance.masterArray = [NSMutableArray new];
}
}
return instance;
}
#end
Usage
[GlobalData.shared.masterArray addObject:"strData"];

NSMutableArray changing old stored data issue

I am parsing JSON and storing that data into NSMutableArray on my homepage. I want to access that data on my other page not after the another, so I am using Singleton Pattern for sharing common data in my homepage. I am storing that NSMutableArray data to Singleton file for common access. In second page i am showing that data in tableview. There is one button which modifies the data but will not change original data i.e homepage arraydata. So I am storing that data into clonearray and updating that clonearray. But when I return back to homepage and in ViewDidAppear after placing breakpoint I am observing my original data is changed.
Please have a look on this issue and correct me where I am doing wrong with my code.
For more reference I added the project link please download and check this: [Project Link][1]
In this project I have created the 2 View Controllers , 1 model class, and one Singleton for common data across all file.
View Controller:
In this file I am parsing JSON and storing in NSMutableArray and also setting the same array data to Singleton file array for common access across all file.
SecondViewController:
In this file I am getting array data from Singleton file and storing in local array.
There is one button to modify data. In modify data function I am modifying the data and storing in the other array for common access (clonearray).
But when I return back to First View Controller and in ViewDidAppear after placing breakpoint, I am observing my original data is changed.
Please check, I don't want my original data to be changed. Please check and suggest me where I am doing wrong with my code.
Your problem because all your property( ViewController->shippingArray, SecondPageController->myshippingarray, PersonDtklSingleton->shippingAddress) point to same array.
You can fix problem by clone array with Deep Copies, to copy original to new array. Make sure all items in original array adopted NSCopying.
SecondPageController
#implementation SecondPageController
...
- (void)viewDidLoad {
[super viewDidLoad];
myshippingarray=[[NSMutableArray alloc]init];
// deep copy
self.myshippingarray = [[NSMutableArray alloc] initWithArray:[[PersonDtklSingleton sharedInstance]shippingAddress] copyItems:YES];
// Do any additional setup after loading the view.
}
...
#end
PersonModel
#implementation PersonModel
#synthesize housernumber,resident,street,city,pincode,defaultAddress;
- (id)copyWithZone:(NSZone *)zone {
PersonModel *copyObj = [PersonModel new];
copyObj.housernumber = [self.housernumber copyWithZone:zone];
copyObj.resident = [self.resident copyWithZone:zone];
copyObj.street = [self.street copyWithZone:zone];
copyObj.city = [self.city copyWithZone:zone];
copyObj.pincode = [self.pincode copyWithZone:zone];
copyObj.defaultAddress = [self.defaultAddress copyWithZone:zone];
return copyObj;
}
#end
If I did't wrong when you update the data it change both of your data since it's referencing the same memory
you need to alloc a new memory and copy the data into a new array
like this
NSMutableArray *newArray=[[NSMutableArray alloc] initWithArray:originalArray copyItems:YES];
You just update the newArray and the original one won't be affected

Bookmark page in xcode6 - Objective-C

I'm trying to create a bookmark page for my app. basically, I want to be able to click on a button in my UIViewController, and have the url of the website I'm currently viewing be saved as a cell in a UITableViewController. The problem is I'm not so sure of the best way to implement this.
I think the way to do it would be to have a mutable array in my tableviewcontroller which I've created here:
#import <UIKit/UIKit.h>
#interface FavoriteViewController : UITableViewController
#property (strong, atomic) NSMutableArray *tableItems;
#end
I could then use the button in the viewController to populate the array. However when I try something like this:
- (IBAction)fave:(id)sender {
[FavoriteViewController.tableItems addObject:[NSString self.faveURL]];
}
I receive an error that property tableItems is not found on FavoriteViewController. Not sure why this is. Anyone have a solution?
Access properties through object instead of directly calling by class name.
- (IBAction)fave:(id)sender {
// If accessing from other class
FavoriteViewController *favVC = ------
[favVC.tableItems addObject:[NSString self.faveURL]];
}
- (IBAction)fave:(id)sender {
// If accessing from same class where you defined your variable
[self.tableItems addObject:[NSString self.faveURL]];
}
If you want to access using class name then you have to static/class methods instead of properties.
[self.tableItems addObject:[NSString self.faveURL]];
You're accessing a class variable with your current code, but tableItems is an instance variable. So if the function fave is in the FavoriteViewController class, then you need to reference self when accessing the instance variable.

how can i create copy pointer to NSArray if my class is singleton class?

I have a singleton class. In this class, i am holding an array of songs. This array should not change! in my app when i choose a song from my song list, the current song is inserted to another variable. This var is Song type ( the array is array of songs ). so when i am writing
_myDataMgr._currSong = [_myDataMgr.songArray objectAtIndex:index];
Every time i will change this currSong Variable the songArray will change because currSong is point to this array. so my question is how i can create a copy of this currSong? i know somthing about NSCopy but i dont know how to use it really. thank you all.
P.S: _myDataMgr is the singleton
You should make your class conform to the NSCopying protocol.
#interface Song : NSObject <NSCopying>
Then, implement the method copyWithZone:
- (id)copyWithZone:(NSZone *)zone
{
id copy = [[[self class] alloc] init];
if (copy) {
// Copy properties here...
}
return copy;
}
When you need a copy of your instance, just call copy. (I recommend to call this when you're inserting the songs into the array in the singleton class.)
[myArray insertObject:[song copy]];

Accessing properties of an object inside array of objects

I have a list of items showing up on a table view.
Every item has its properties such as name, pic, rank etc'.
My goal is, every time the user selects a row the item with its properties will be added to a new list.
I've created a new list called listOfBugs and because i want it to be global i've allocated and initialized it inside viewDidLoad. (Is that a proper thing to do?)
Here is my code:
MasterViewController.h
#interface MasterViewController : UITableViewController
{
NSMutableArray *listOfBugs;
}
#property (strong) NSMutableArray *bugs;
MasterViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
listOfBugs = [[NSMutableArray alloc]init];
self.title = #"Scary Bugs";
}
...
...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
ScaryBugDoc *bug = [self.bugs objectAtIndex:indexPath.row];
UIAlertView *messageAlert = [[UIAlertView alloc]
initWithTitle:#"Row Selected" message:bug.data.title delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[messageAlert show];
[listOfBugs addObject:bug];
NSLog(#"this is %#",listOfBugs);
}
Using NSLog I can see that the objects are added:
ScaryBugs[1195:11303] this is <ScaryBugDoc: 0x75546e0>
2012-12-05 17:45:13.100
ScaryBugs[1195:11303] this is <ScaryBugDoc: 0x75546e0>
I have a few questions.
1.How can I access the properties of the objects inside of the array listOfBugs ?
Update: This worked for me:
NSLog(#"this is %#",((ScaryBugDoc *)[listOfBugs objectAtIndex:0]).data.title);
But I can't access the listOfBugs from another class.
I turned it into a property as suggested to make my life easier but still can't access it from another class.
For example in listOfBugsViewController.m return [_listOfBugs count]; will give me the error Use of undeclared identifier '_listOfBugs'
2.I want to be abale to populate a table view with the customized list, how can i do that?
After accomplishing that I would like to save the list as a plist and also add and remove objects from it at ease so I need to take that under consideration.
This is the code that I'm based on, I only made a few adjustments to create the new list
This is really two questions:
1) How do I make my property a public property which can be accessed by other classes?
You do this just like you did with your bugs property. Add this to your .h file:
#property (strong) NSMutableArray *newList;
Note that if you aren't using different threads, you can make it a little more efficient by using the nonatomic property as well (#property (nonatomic, strong)).
Once you do that, you don't need your iVar declaration because it will automatically be generated for you. (i.e. you can remove NSMutableArray *newList;.)
2) How do I access an object in an array?
Objects in an array are stored as an id object, meaning that it is a "generic" object. If you know what type of object is stored, then you need to tell the compiler what it is so that it knows what properties and methods are appropriate for that class. You do this by casting the variable to the proper type:
ScaryBugDoc *bug = (ScaryBugDoc *)[self.newList objectAtIndex:0];
Then, you can access the properties of the object, assuming that they are public (as covered in point 1 above) like this:
NSLog(#"this is %s", bug.data.tile);
Okay, so based from the comments, this should work:
Album* tempAlbum = [albumList objectAtIndex:i];
//now you can access album's properties
Song* tempSong = [album.songs objectAtIndex:j];
//now you can access song's properties
This can be simplified down to:
Song* someSong = [((Album)[albumList objectAtIndex:i]).songs objectAtIndex:j];
When returning an object from an NSArray, or a collection object like that it will return a generic id object. This will need to be typecasted to the expected object so you can access the right properties.

Resources