It seems like I have a problem and don't know if I'm doing this right since I'm just starting objective c.
Right now I have two files
Stores.h
#import<Foundation/Foundation.h>
#import<MapKit/MapKit.h>
#interface Stores: NSObject
#property(nonatomic,strong) NSString *storeName;
#property(nonatomic,strong) NSMutableArray *MenuItems;
#end
Stores.m
#import "Stores.h"
#synthesize storeName,MenuItems;
#end
Menu.h
#import<Foundation/Foundation.h>
#interface Menu: NSObject
#property(nonatomic,strong) NSString *MenuItemDescription;
#property(nonatomic) int MenuItemPrice;
#end
Menu.m
#import "Menu.h"
#synthesize MenuItemDescription,MenuItemPrice;
#end
ViewController.m
#import "ViewController.h"
#import "Stores.h"
#import "Menu.h"
#interface ViewController ()
#end
#implementation ViewController
NSMutableArray *stores;
-(void) viewDidLoad
{
[super viewDidLoad];
stores = [[NSMutableArray alloc]init];
Stores *store = [[Stores alloc]init];
[store setStoreName:#"Store1"];
Menu *menuItem = [[Menu alloc]init];
[menuItem setMenuItemDescription:#"Item1"];
[menuItem setMenuItemPrice: 7]
[store.MenuItems addObject:menuItem]; //won't add menuItem to store.MenuItems
[stores addObject:store];
}
#end
So it doesn't end up adding any object to store.
If I run it in debug it says that MenuItems has zero objects.
I know I'm doing something wrong but like I said I'm new to iOS.
You did not (at least in the code you show) alloc/create/assign MenuItems, so it will still be nil. Calling addObject (or anything) on nil is just a no-op.
Try this
Stores *store = [[Stores alloc]init];
store.MenuItems = [NSMutableArray arrayWithCapacity: 10];
Related
I am trying add a Song* object to a Mutable array and I am stumped as the count of the array is not increasing in spite of adding the object.
Song.h
#import <Foundation/Foundation.h>
#interface Song : NSObject
#property(copy, nonatomic) NSString *title, *album, *artist;
#property(copy, nonatomic) NSNumber *playTime;
#end
Song.m
#import "Song.h"
#implementation Song
#end
Playlist.h
#import <Foundation/Foundation.h>
#class Song;
#interface Playlist : NSObject
#property(copy, nonatomic) NSMutableArray *playListArray;
-(void) addSong: (Song *) tempSongToBeAdded;
-(void) removeSong: (Song *) tempSongToBeremoved;
-(void) listOfSongs;
-(NSUInteger) entries;
#end
Playlist.m
#import "Playlist.h"
#import "Song.h"
#implementation Playlist
-(void) addSong: (Song *) tempSongToBeAdded{
NSLog(#"%s song is being added.", [tempSongToBeAdded.title UTF8String]);
[self.playListArray addObject:tempSongToBeAdded];
}
-(void) removeSong: (Song *) tempSongToBeremoved{
[self.playListArray removeObject:tempSongToBeremoved];
}
-(NSUInteger) entries{
return [self.playListArray count];
}
-(void) listOfSongs{
NSLog(#"Hi");
for (Song *tempSong in self.playListArray) {
NSLog(#"title: %s", [tempSong.title UTF8String]);
}
}
#end
Main.m
#import <Foundation/Foundation.h>
#import "Song.h"
#import "Playlist.h"
int main(int argc, const char * argv[])
{
#autoreleasepool {
Song *song1 = [[Song alloc] init];
song1.title = #"Manasa";
song1.album = #"Ye Maya Chesava";
song1.artist = #"A. R. Rahman";
song1.playTime = [NSNumber numberWithDouble:4.56];
Playlist *playlist1 = [[Playlist alloc] init];
[playlist1 addSong:song1];
NSLog(#"The total number of songs are %lu",[playlist1 entries]);
[playlist1 listOfSongs];
}
return 0;
}
I am getting the entries in the playlist as 0 and and the list of songs as empty. I am not getting any compile errors and I have no idea why the objects are not getting added to the array.
Your variable playListArray is never initialized and is always nil. You need to initialize it using:
playListArray = [[NSMutableArray] alloc] init];
You can add an init method in your Playlist class where you initialize this object.
- (id)init
{
self = [super init];
if (self)
{
playListArray = [[NSMutableArray] alloc] init];
}
return self;
}
EDIT:
The problem seems to be how you declared the property
#property(copy, nonatomic) NSMutableArray *playListArray;
It is declared as copy, that means that even when you do playListArray = [[NSMutableArray] alloc] init], your variable playListArray gets a copy of the initialized array, but the copy protocol is inherited from NSArray, not from NSMutableArray, so you get an immutable array. You can check this in the NSMutableArray documentation. You need to change copy for retain (you're not using ARC, right?).
In fact I see that you're using copy for most of your properties, if there's no particular reason for this, I would change them to retain.
I know theres a better solution using arc4random (it's on my to-try-out-function list), but I wanted to try out using the rand() and stand(time(NULL)) function first. I've created a NSMutableArray and chuck it with 5 data. Testing out how many number it has was fine. But when I tried to use the button function to load the object it return me with object <sampleData: 0x9a2f0e0>
- (IBAction)generateNumber:(id)sender {
srand(time(NULL));
NSInteger number =rand()% ds.count ;
label.text = [NSString stringWithFormat:#"object %#", [ds objectAtIndex:number] ];
NSLog(#"%#",label.text);
}
While I feel the main cause is the method itself, I've paste the rest of the code below just incase i made any error somewhere.
ViewController.h
#import <UIKit/UIKit.h>
#import "sampleData.h"
#import "sampleDataDAO.h"
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *label;
#property (weak, nonatomic) IBOutlet UIButton *onHitMePressed;
- (IBAction)generateNumber:(id)sender;
#property(nonatomic, strong) sampleDataDAO *daoDS;
#property(nonatomic, strong) NSMutableArray *ds;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize label;
#synthesize onHitMePressed;
#synthesize daoDS,ds;
- (void)viewDidLoad
{
[super viewDidLoad];
daoDS = [[sampleDataDAO alloc] init];
self.ds = daoDS.PopulateDataSource;
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[self setLabel:nil];
[self setOnHitMePressed:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)generateNumber:(id)sender {
srand(time(NULL));
NSInteger number =rand()% ds.count ;
label.text = [NSString stringWithFormat:#"object %#", [ds objectAtIndex:number] ];
NSLog(#"%#",label.text);
}
#end
sampleData.h
#import <Foundation/Foundation.h>
#interface sampleData : NSObject
#property (strong,nonatomic) NSString * object;
#end
sampleData.m
#import "sampleData.h"
#implementation sampleData
#synthesize object;
#end
sampleDataDAO.h
#import <Foundation/Foundation.h>
#import "sampleData.h"
#interface sampleDataDAO : NSObject
#property(strong,nonatomic)NSMutableArray*someDataArray;
-(NSMutableArray *)PopulateDataSource;
#end
sampleDataDAO.m
#import "sampleDataDAO.h"
#implementation sampleDataDAO
#synthesize someDataArray;
-(NSMutableArray *)PopulateDataSource
{
someDataArray = [[NSMutableArray alloc]init];
sampleData * myData = [[sampleData alloc]init];
myData.object= #"object 1";
[someDataArray addObject:myData];
myData=nil;
myData = [[sampleData alloc] init];
myData.object= #"object 2";
[someDataArray addObject:myData];
myData=nil;
myData = [[sampleData alloc] init];
myData.object= #"object 3";
[someDataArray addObject:myData];
myData=nil;
myData = [[sampleData alloc] init];
myData.object= #"object 4";
[someDataArray addObject:myData];
myData=nil;
myData = [[sampleData alloc] init];
myData.object= #"object 5";
[someDataArray addObject:myData];
myData=nil;
return someDataArray;
}
#end
what i guess is going on is that nslog function cant print the data inside your sample data class because its not a standard class. not standard classes must implement the "description" method. What you get when you print out your class is the pointer to it, because nslog has no way of knowing how to print out the data in your class.
if what you want to print on that label/nslog is the nsstring inside your class "sampledata" you should access the property.
this can be done in the following way:
SampleData *instanceOfSampleData = (SampleData*)[ds objectAtIndex:number];
label.text = [NSString stringWithFormat:#"object %#", instanceOfSampleData.object];
So I'm creating an array called fruits which I would like to share between multiple views. This is my code:
#import <foundation/Foundation.h>
#interface MyManager : NSObject {
NSMutableArray *fruits;
}
#property (nonatomic, retain) NSMutableArray *fruits;
+ (id)sharedManager;
#end
#import "MyManager.h"
static MyManager *sharedMyManager = nil;
#implementation MyManager
#synthesize fruits;
#pragma mark Singleton Methods
+ (id)sharedManager {
#synchronized(self) {
if (sharedMyManager == nil)
sharedMyManager = [[self alloc] init];
}
return sharedMyManager;
}
- (id)init {
if ((self = [super init])) {
fruits = [[NSMutableArray alloc] init];
}
return self;
}
-(void) dealloc{
self.fruits = nil;
[super dealloc];
}
#end
Now I'm using the following code so that I can use workouts in the new view
#import "MyManager.h"
#interface Chest : UIViewController {
IBOutlet MyManager *fruits;
}
#property (nonatomic, retain) IBOutlet MyManager *fruits;
-(IBAction) goToList: (id) sender;
#end
When a button is clicked, goToList is called, and I populate my array, fruits
#import "Chest.h"
#implementation Chest
#synthesize fruits;
-(IBAction) goToList:(id)sender{
MyManager *fruits = [MyManager sharedManager];
NSString *filePath;
NSString *fileContents;
filePath = [[NSBundle mainBundle] pathForResource:#"chest_strength" ofType:#"csv"];
fileContents = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
fruits = [fileContents componentsSeparatedByString:#"\n"];
}
When I output the elements of *fruits in this view, everything works fine. Now when I try to access this same variable in the other view, it says the array is null. Here's the code for the second view:
#interface List : UIViewController {
IBOutlet MyManager *fruits;
}
#property (nonatomic, retain) IBOutlet MyManager *fruits;
#end
#import "List.h"
#import "MyManager.h"
#implementation List
#synthesize fruits
NSLog(#"%#", fruits); //This is the part that isn't displaying correctly. I'm getting a null here
So my question is, how do I do this so that I can get the array fruits that I populated in Chest and use it in List so that I can display the contents of the array in that view?
Thank you to everybody who answers. This problem is seriously bogging me down and I need to finish this project ASAP. Much appreciated.
You've changed a few things in this question but the fundamental problem remains: the array is a property of your singleton, and you are not treating it as such.
Whenever you refer to the array, outside of the singleton, do it like this:
[MyManager sharedManager].fruits
If you are accessing it frequently, you can create a local ivar, but you certainly wouldn't have it as an IBOutlet, which you are doing in your last code sample. How is that ever going to be set?
I have a small piece of code that sets the NSString (strUsername) of the class Username to the value which is typed into a UITextField and then a button is pressed. This works fine:
UsernameViewController.m
#import <UIKit/UIKit.h>
#import "Username.h"
#interface UsernameViewController : UIViewController
{
Username *username;
__weak IBOutlet UITextField *test;
}
#property (nonatomic, retain)IBOutlet UITextField *txtUsername;
#property (nonatomic, retain) IBOutlet UITextField *test;
-(IBAction)setUsername;
#end
#import "UsernameViewController.h"
#import "Username.h"
#implementation UsernameViewController
#synthesize test=_test;
- (void)viewDidLoad
{
[super viewDidLoad];
username = [[Username alloc] init];
}
-(IBAction)setUsername
{
NSString *inputUsername = self.test.text;
NSLog(#"inputUsername is: %#", inputUsername);
username.strUsername = inputUsername;
NSLog(#"the username.strUsername is now: %#", username.strUsername);
}
My NSLog output shows that the UItextfield input and NSString setter are working:
LocNews1[6699:707] inputUsername is: Harry brown
LocNews1[6699:707] the username.strUsername is now: Harry brown
Now when it hit the back button on this view it return me back to a UITableViewController. I then perform a pull down to refresh action and its called the following method:
TestViewController.m (UITableViewController type)
#import "TestViewController.h"
#import "ViewController.h"
#import "DetailViewController.h"
#import "AppDelegate.h"
#import "NewsArticle.h"
#import "ResultsCustomCell.h"
#import "XMLParser.h"
#implementation TestViewController
//some code
- (void)addItem
{
username = [[Username alloc] init];
// Use XMLparser to check for updated new feeds.
if(username.strUsername != NULL)
{
NSLog(#"ViewController username.strUsername is:%#",username.strUsername);
activeUsername = username.strUsername;
}
else
{
NSLog(#"%#",username.strUsername);
activeUsername = #"";
}
NSString *myLat = [[NSString alloc] initWithFormat:#"%f", locationManager.location.coordinate.latitude];
NSString *mylong = [[NSString alloc] initWithFormat:#"%f", locationManager.location.coordinate.longitude];
XMLParser *parseQuestionnaire = [[XMLParser alloc] init];
NSLog(#"username %#",activeUsername);
newsArticle = [parseQuestionnaire parseXML:myLat:mylong:activeUsername];
[self.tableView reloadData];
[self stopLoading];
}
However this shows the NSLog output as:
LocNews1[6699:707] ViewController username.strUsername is:
As you can see the string has been set in UsernameViewController.m but when I try and call the string back in TestViewController.m is appears to be blank (there is no null in the NSLog, just blank);
What could be causing this?
EDIT: Username.h/m
#import <Foundation/Foundation.h>
#interface Username : NSObject
{
NSString *strUsername;
}
#property (nonatomic, retain) NSString *strUsername;
#end
#import "Username.h"
#implementation Username
#synthesize strUsername;
-(id)init
{
strUsername = [[NSString alloc] init];
return self;
}
#end
Note: Username is declared in both TestViewController.h and UsernameViewController.h like: Username *username;
The username instance variable in that instance of UsernameViewController is completely unrelated to the username instance variable in the instance of TestViewController. You'll need to store the variable in a place that both controllers know about or pass it between them if you want them both to have access. Simply having two variables with the same name doesn't connect them in any way.
I have these two classes MobRec & MobDef and I want to reference an array pointer of (MobDef) *mobInfo from MobRec. #import the mobdefs.h file in MobRec.h or .m but no luck any ideas?
MobRec.h
// Basic class unit
#interface MobRec : NSObject {
NSString *mName;
int speed;
}
#end
MobDef.h
// Master Class holding an array of units
#interface MobDef : NSObject {
NSMutableArray *mobInfo;
}
#property(retain) NSMutableArray *mobInfo;
#end
MobDef.m
#synthesize MobInfo;
- (id)init { // to add a new node and initialize it
mobInfo = [[NSMutableArray alloc] init];
MobRec *aNewMobRec = [[MobRec alloc] init];
[mobInfo addObject:aNewMobRec];
[aNewMobRec release];
}
The problem is that individual files have no knowledge of other files in your project, since Objective-C is a derivative of C. You need to #import the header files of any other classes that you need to use:
// ModDef.m
#import "MobDef.h"
#import "ModRec.h"
#implementation MobDef
#synthesize mobInfo; // case matters here
- (id)init
{
mobInfo = [[NSMutableArray alloc] init];
MobRec* aNewMobRec = [[MobRec alloc] init];
[mobInfo addObject:aNewMobRec];
[aNewMobRec release];
}
#end
Well, your #synthesize doesn't match #property declaration - you're declaring properties for mobInfo but generating synthesized accessors for MobInfo.
Of are you getting some other error?