How to create a simple class that holds an array - objective-c

Ok, begginer question here.
I create a class to hold a list of my dvds, h file:
#import <Foundation/Foundation.h>
#interface Films : NSObject
#property NSMutableArray *horrorFilms;
- (NSMutableArray*) createListOfHorrorFilms;
#end
m file:
#import "Films.h"
#implementation Films
- (NSMutableArray*) createListOfHorrorFilms{
self.horrorFilms = [[NSMutableArray alloc] initWithObjects:#"The Shinning", #"Carrie",#"The Blair Witch Poject", nil];
return self.horrorFilms;
}
#end
Would this work? If not, what is the proper way of doing it? Thanks

Hi You could prefer plist. if you are using more static values in your class. Which will be easy to modify and handle in future.
For doing the above case in plist.
Create a plist (Right click Project folder->New File -> resources -> select Property List), Assign a plist name for example horrorFilms.
horrorFilms plist will be saved in your project folder.
Select horrorFilms and change root plist type to NSArray from NSDictionary.
Add Itmes (as String) to your root plist Array
-Go to Your .m Controller class. Add the following method to fetch plist.
- (NSArray *)horrorFilmsList
{
NSString *plistPath = [[NSBundle mainBundle] pathForResource:#"horrorFilms" ofType:#"plist"];
NSArray * arrhorrorFilms = [[NSArray alloc] initWithContentsOfFile:plistPath];
return arrhorrorFilms;
}
6 fetch your plist array anywhere by [self horrorFilmsList. If you want to see in log try this in viewDidLoad NSLog(#"\nHorror Films-->%#",[self horrorFilmsList]);

Related

NSMutableArray not retaining values outside of method

Ive been trying to solve this for the past one hour, but still had no luck
I have an NSMutableArray instance variable which holds objects in the following class:The array successfully gets populated in the method i populate it in, but it shows up as empty in all other methods/classes
.h file...
#import "RedditPostItem.h"
#interface RedditRepository : NSObject
#property (nonatomic, strong) NSMutableArray *redditPosts; //<<** this
is the problem array
#property (nonatomic, strong,readwrite) NSDictionary *allJSONData;
#property (nonatomic, strong,readwrite) NSMutableData *incomingData;
- (void)getPosts;
- (void)printAllTitles;
#end
.m file
#implementation RedditRepository . . #synthesize
redditPosts=_redditPosts;
. .
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
self.redditPosts = [[NSMutableArray alloc] initWithCapacity:20];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//parse json data
_allJSONData = [NSJSONSerialization JSONObjectWithData:_incomingData options:0 error:nil];
NSDictionary *dataDictionary = [_allJSONData objectForKey:#"data"];
NSArray *arrayOfChildren = [dataDictionary objectForKey:#"children"];
for (NSDictionary *diction in arrayOfChildren) {
NSDictionary *childrenData = [diction objectForKey:#"data"];
RedditPostItem *postItem = [[RedditPostItem alloc]initWithAPIResponse:childrenData];
//******************************* add to array.....
[self.redditPosts addObject:postItem];
}
//******* if i iterate through 'self.redditPosts' i can see everything uptill this point and the array successfully gets
populated//
}
//********* if I execute any operation from any other method in this
class or any other class...the array shows up as empty!!***//
- (void)printAllTitles{
if(self.redditPosts == nil) {
NSLog(#"array is empty....."); ///always shows up as empty for some reason<<<<<< }
}
Your array is being populated asynchronously - you're downloading from a URL in the background while your user interface continues to run in the foreground. The reason you're seeing it as empty is because it hasn't been populated yet. Your app should be written in such a way that it can deal with data not being available instantaneously and being able to update itself when the data becomes available.
If that doesn't get you on the right track, please ask a more specific question about the problem you're trying to solve.

Files and their initialization

A quick question i hope.
I'm new to xcode and IOS apps, and have made a bunch of tutorials but i still don't get one thing. If i make a new file (StaticData.h, StaticData.m) and in the .h I declare a public property NSMutableArray. And in the .m file i fill it statically.
#implementation StaticData
-(NSMutableArray *)staticArray
{
NSString *value0 = #"test)";
return [NSMutableArray arrayWithObjects:value0, nil];
}
#end
Now i import the .h file in a viewcontroller and try to load the data in the table. the array is empty. So i set a breakpoint but it is never hit.
So how do i init a file without a view?
You need to use your file by creating an instance of your class StaticData like this:
StaticData *data = [[StaticData alloc] init];
Don't forget to delete data when you are ready!

NSDictionary add -objectAtIndex by category

I'm writing custom patch for Quartz Composer and I work with structures as input. Structure are NSDictionary in Obj-C so I use NSDictionary's methods to deal with these structures. Depending on how I build these structures key can be NSString type or NSNumber.
Usually QC doesn't give named structures and keys are "0"..."n" or 0...n so I've decided to add -objectAtIndex in a NSDictionary category :
NSDictionary+Utils.h
#import <Foundation/Foundation.h>
#interface NSDictionary (Utils)
- (id)objectAtIndex:(NSInteger)index;
#end
NSDictionary+Utils.m
#import "NSDictionary+Utils.h"
#implementation NSDictionary (Utils)
- (id)objectAtIndex:(NSInteger)index
{
NSString* key = [NSString stringWithFormat:#"%d", index];
return [self objectForKey:key];
}
#end
It works perfectly for one of my project in which I build a structure using Kineme Struc Maker patch.
In another project I use the Queue patch provided by apple. Keys are not NSString type but NSNumber type. I've rewritten the code to be compliant with NSNumber keys :
NSDictionary+Utils.m
#implementation NSDictionary (Utils)
- (id)objectAtIndex:(NSInteger)index
{
NSNumber* key = [NSNumber numberWithInteger:index];
return [self objectForKey:key];
}
#end
Unfortunately it always gives a null value but using :
[self.inputSoundStruct objectForKey:[NSNumber numberWithInteger:0]]
Why does this line of code works but not objectAtIndex ? I must be missing something but what ?

Objective C - How to add a method to an existing class?

How can i add a new method to NSString class.
I need to create a method that get's called on a string and returns an NSDictionary.
I know that i can simply create a function that gets a string and return an nsdictionary, but i want to know how to add it to an existing class.
NSString *myStr = #"some json string";
NSDictionary *dictionary = [myStr getJSONData];
You can use Objective-C categories. For example to add on to NSString define the following in a new .h/.m file:
#interface NSString (CategoryName)
-(NSString *) aNewMethod;
#end

Accessing NSMutableDictionary Across Classes

I have declared an NSMutableDictionary object in AppController.h and initialized in the corresponding AppController.m file.
AppController.h
#import <Cocoa/Cocoa.h>
#interface AppController : NSObject {
NSMutableDictionary *uberDict;
}
AppController.m
#import "AppController.h"
#implementation AppController
- (id)init
{
uberDict = [NSMutableDictionary new];
return self;
}
Now I want to use the NSMutableDictionary object in another view, flashcardView. I add/remove items in the dictionary using methods in the AppController class and want to use the same dictionary (with the current items still present in it) in the flashcardView view. The problem is that I don't know how to access the dictionary object from outside AppController. How would I do that?
from flashcardView.m
- (void)setAndCheckString
{
NSArray *keys = [uberDict allKeys];
NSString *i;
for (i in keys) {
string = i;
NSLog(#"%#", string);
}
}
Here's where the problem lies. What do I do with uberDict to make this work? Thanks!
While I encourage you to look at alternative design patterns, to do what you're looking for you simply need to add a method (or property) to access uberDict to AppController. As a property, the code would be:
#interface AppController : NSObject {
NSMutableDictionary *uberDict;
}
#property (readonly) NSMutableArray *uberDict;
#end
in the AppController.h file, and just add a one line #synthesize uberDict; inside the AppContoller implementation (before the #end). Don't worry about the (readonly) -- this means that the object getting the uberDict cannot set it to a new dictionary, but still can modify the contents of the dict and read from it.