I'm stumped. NSLog verifies the object is what it's supposed to be, but adding the object to array isn't working - objective-c

jeoData is a singleton...the table displays just fine, NSLog verifies the correct row is selected, however, jeoData.crewList.count returns zero after adding the object to the NSMutableArray...
in the jeoData singleton, employeeList is initialized identically to crewList.
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Employee *employee = [jeoData.employeeList objectAtIndex:indexPath.row];
[jeoData.crewList addObject:employee];
NSLog(#"SelectCrewVC: added: %# %#", employee.firstName, employee.lastName);
NSLog(#" total selected: %lu", (unsigned long)jeoData.crewList.count);
}
NSLog:
2014-10-17 15:09:41.590 SaveAndLoad[98371:414247] SelectCrewVC: added: Jacob Johnson
2014-10-17 15:09:41.591 SaveAndLoad[98371:414247] total selected: 0
...even the didDeselectRow selects the correct object to display, but I cannot figure out why I can't get the object into the crewList array.
Any help would be greatly appreciated, because I'm stumped.
EDIT: adding code as per request
JEOData.m (singleton... where init occurs)
#implementation JEOData
#synthesize employeeList;
#synthesize leaseList;
#synthesize crewList;
#synthesize workReport;
+(id)sharedManager {
static JEOData *sharedJEOData = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^ {
sharedJEOData = [[self alloc] init];
});
return sharedJEOData;
}
-(id)init {
if (self = [super init]) {
employeeList = [[NSMutableArray alloc] init];
leaseList = [[NSMutableArray alloc] init];
crewList = [[NSMutableArray alloc] init];
workReport = [[NSMutableArray alloc] init];
}
return self;
}
#end
jeoData is declared in the #interface of the header file of the View Controller
#interface SelectCrewViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
JEOData *jeoData;
NSMutableArray *crewList; <---created only in troubleshooting, unused now
}
ViewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
jeoData = [JEOData sharedManager];
self.crewSelectTable.allowsMultipleSelection = YES;
NSLog(#"Num of employees total :%lu", (unsigned long)jeoData.employeeList.count);
NSLog(#" employees in crew list: %lu", (unsigned long)jeoData.crewList.count);
}
NSLog returns:
2014-10-17 15:09:39.473 SaveAndLoad[98371:414247] Num of employees total :3
2014-10-17 15:09:39.474 SaveAndLoad[98371:414247] employees in crew list: 0
So, you can see that jeoData.employeeList contains the right objects, as does jeoData.leaseList. I know that DidSelectRows is being called because of the NSLog, so I know that the Employee object is well and alive, yet it will not let me add the little bugger to the crewList mutable array.
I am fairly certain that I am just overlooking something, yet I am at a loss to see what it is.
Please, help us, Obi-wan Kenobi, you're our only hope.

Solved, ok, I knew I was overlooking something...
The first initializing of the jeoData singleton class happens in the initial view controller, however, since nothing is actually added to the crewList mutable array, once the segue to the problematic view controller was made, the crewList array disappeared, rather than be retained like the employeeList.
I called the init function on jeoData.crewList in viewDidLoad and it allows me to add/remove from the array.
The only thing I need to figure out now is if it will still retain the objects in the array after moving to yet ANOTHER view controller.

Related

Singleton dictionary is empty, and I don't see why

I have an iOS app that matches incoming text fields to standard fields used to import records. My problem is that a NSMutableDictionary that uses those fields is empty! Here is the code that saves the mapping:
-(void)mapUserFields: (id) sender { // move contents of each textField when user has finished entering it
SingletonDictionary *sd = [SingletonDictionary sharedDictionary];
UITextField *tf = (UITextField *)sender; // textfield contains the pointer to user's half of the equation
int tagValue = (int)tf.tag; // get the tag value
[sd.dictionaryOfUserIndexes setObject:tf.text forKey:[NSString stringWithFormat:#"%d", tagValue]]; // value found in textField id'd by tag
NSLog(#"\nfield.text: %# tagValue: %d nsd.count: %d\n",tf.text, tagValue, sd.dictionaryOfUserIndexes.count);
}
This is the result of the NSLog:
field.text: 1 tagValue: 38 nsd.count: 0
This is the definition of the singleton in the .h file:
#property (nonatomic, retain) NSMutableDictionary *dictionaryOfUserIndexes;
This is the code to initialize the singleton in the .m file:
//-- SingletonDictionaryOfUserIDs --
+ (id) sharedDictionary {
static dispatch_once_t dispatchOncePredicate = 0;
__strong static id _sharedObject = nil;
dispatch_once(&dispatchOncePredicate, ^{
_sharedObject = [[self alloc] init];
});
return _sharedObject;
}
-(id) init {
self = [super init];
if (self) {
dictionaryOfUserIndexes = [NSMutableDictionary new];
}
return self;
}
#end
I believe my problem is because the sd.dictionaryOfUserIndexes is not initialized, but I am not sure if that's true, and if so, how to initialize it (I tried several different variants, all of which created build errors). I looked on SO and Google, but found nothing that addresses this particular issue. Help would be greatly appreciated!
There are a few things we could improve in this code, but the only thing wrong with it is the reference to dictionaryOfUserIndexes in the init method. The code as posted wouldn't compile, unless: (a) you have a line like:
#synthesize dictionaryOfUserIndexes = dictionaryOfUserIndexes;
so that the backing variable is named without the default _ prefix, or (b) you refer to the ivar with the default prefix, as in:
_dictionaryOfUserIndexes = [NSMutableDictionary new];
The other way -- preferable in most every context except within an init method -- is to use the synthesized setter, like:
self.dictionaryOfUserIndexes = [NSMutableDictionary new];
But with that change alone (so it will compile) your code runs fine, adds a value to the dictionary and logs an incremented count.

My NSString is determined to equal null, infuriating

This has been bugging me all night, It doesn't make any sense. This function returns whatever it's supposed to. EG, the issueName.
-(id)initWithIssue:(NSString *)string {
self = [super initWithNibName:nil bundle:nil];
if (self) {
NSString *thing = string;
issueName = [[NSString alloc]initWithString:thing];
NSLog(#"The issue name = %#", issueName);
}
return self;
}
However if I try to access 'issueName' in the viewDidLoad: nothing, it's equal to null no matter what I do. I've tried cleaning, setting a custom setter, switching between a property or a Ivar... ect. What's so infuriating is that this string just disappears at this point in the programe.
What the hell is going on, this is infuriating.
Edit
This the the entire code that is relevant. And how I started off.
Dot h file:
#interface BFPaidAreaViewController : UITabBarController <BFNewsTableViewControllerDelegate> {
NSString *issueName;
}
-(id)initWithIssue:(NSString *)string;
Dot m file:
-(id)initWithIssue:(NSString *)string {
self = [super init];
if (self) {
// PLPiper I had it that way before, because I was fiddling out of frustration
issueName = [[NSString alloc] initWithString:string];
NSLog(#"This is Called, the issue name is equal to = %#", issueName);
}
return self;
}
-(void)viewDidLoad {
[super viewDidLoad];
NSLog(#"The issue = %#", issueName);
}
I'm calling the view controller like so:
BFPaidAreaViewController *pavc = [[BFPaidAreaViewController alloc]initWithIssue:#"test"];
This will log:
This is Called, the issue name is equal to = test
The issue = (null)
New Edit
Found the problem. It's a UITableViewController. Strange, when I change it's class to a UIViewController it works. Is this a bug or just normal behaviour? But more pressing, how to I get round this limitation?
(Just to explain what I've done UI wise, the UITabBarController is in a modal View. This works fine with a UIViewController.)
God Awful Fix
-(id)initWithIssue:(NSString *)string {
self = [super initWithNibName:nil bundle:nil];
if (self) {
NSString *thing = string;
issueName = [[NSString alloc]initWithString:thing];
NSLog(#"The issue name = %#", issueName);
}
[self viewDidLoad];
return self;
}
Makes me feel dirty. But it will have to do for now, I can continue. If anyone can think of a solution please tell. Sorry about my feistiness, it was incredibly frustrating listening to people say, 'what the hell is this?? what is issueName?? an ivar??' when it was really implicit in the question.
Okay, first of all, replace:
self = [super initWithNibName:nil bundle:nil]; // Unneeded nil arguments
with:
self = [super init]; // Equivalent method, less processing involved.
Secondly, replace:
NSString *thing = string;
issueName = [[NSString alloc]initWithString:thing];
with just:
_issueName = [[NSString alloc] initWithString:string];
If issueName is a property (and you haven't #sythesized it to anything else) its representation should be _issueName.
The above fixes are more or less just make the code more succinct. The issue is probably with the code in viewDidLoad: (See below).
Now you can initialise your Issue object, and use the following code to display the issue name:
// Init:
Issue *myIssue = [[Issue alloc] initWithIssue:#"Example Issue"];
// Log:
NSLog(#"%#", myIssue.issueName);
And the log should show:
Example Issue
can you try this:
make the issueName a property, like
#property (strong, nonatomic) NSString *issueName;
then use it like this,
-(id)initWithIssue:(NSString *)string {
self = [super initWithNibName:nil bundle:nil];
if (self) {
NSLog(#"The string = %#", string);
self.issueName = string;
NSLog(#"The issue name = %#", issueName);
}
return self;
}
if you are using the automated synthetized property (i.e not declaring the #synthentize manually for the issueName), then your iVar will be called _issueName instead of issueName
what do you get from the above code ?
I find this somewhat curious. You call [super initWithNibName:nil bundle:nil]. This leads me to believe that this might be a subclass of NSViewController. If you init an NSViewController like this, barring some other, pretty non-standard stuff, -viewDidLoad probably won't get called because there's no NIB to be loaded (because you passed nil to super). But clearly you're setting a breakpoint in -viewDidLoad so it's getting called (on something). This makes me think that you have this class specified in a XIB somewhere as a File's Owner or as a NIB-loaded custom object. If that's the case, it leads me to believe that the instance you're init-ing and the instance on which -viewDidLoad is being called aren't the same instance. You can confirm this for yourself by putting NSLog(#"self: %p", self); in each method and seeing whether they are the same or different.
If the instance that is getting a call to -viewDidLoad is NIB-loaded, then your init method won't be called. Instead it will use -initWithCoder
If you can elaborate on the situation here (i.e. how this is getting instantiated, are there any XIBs involved, etc), I will edit my answer to provide more help, but I don't think there's enough information here to be truly helpful.
I feel your frustration. Assuming standard behavior, any of the suggestions here should have worked. This only reinforces my suspicion that these are not the same instance (between -initWithIssue and -viewDidLoad.

How to keep data in a NSMutableArray

AAA.m:
- (void)keepCurrentArray:(id)object
{
_currentTest=[[NSMutableArray alloc]init];
[_currentTest addObject:#"one"];
[_currentTest addObject:#"two"];
[_currentTest addObject:object];
NSLog(#"My Array is:%#",_currentTest);
}
Class BBB.m is passing objects to class AAA.
Right now if i'm passing X to the above method so the array will be: one,two,X . Then i'll send it Y and the array will be one,two,Y instead of what i want to accomplish: one,two,x,one,two,y.
Is that because I'm alloc and init _currentTest every time? How can I solve it?
Update:
I had a few suggestions on how to solve this and none of them worked for me. I've created a new project with just the code in the answers and i'm still getting the same result when I try to add the second object i get: one, two, test instead of one,two,test,one,two,test
Yes, it's because that you're alloc and init-ing every time you run that method. Instead, put _currentTest = [[NSMutableArray alloc] init]; in AAA.m's init method.
AAA.m
-(id)init
{
if ((self = [super init]))
_currentTest = [[NSMutableArray alloc] init];
return self;
}
- (void)keepCurrentArray:(id)object
{
[_currentTest addObject:#"one"];
[_currentTest addObject:#"two"];
[_currentTest addObject:object];
NSLog(#"My Array is:%#",_currentTest);
}
_currentTest=[[NSMutableArray alloc]init]; in a method is never a good thing!!!
As per naming convention it seems to be a property to the AAA Class. So for property, the alloc+init should be either in init or awakeFromNib. So that if is initialized just once.
However in some situations init is called more than once then your previous values are lost and new set are added.
So what you can do is make another class and put this _currentTest Array there and make it static and use it here. I hope this will work fine. And make sure in the init method of that class it is initialized just once, as :
//**this is not compiled and checked may contains typo and errors**
#implementation Storage
static NSMutableArray *yourStaticArray;
-(id)init{
self = [super init];
if (self) {
if (!yourStaticArray) {
yourStaticArray=[NSMutableArray new];
}
}
return self;
}
-(void)addYourStaticArray:(NSString *)val{
[yourStaticArray addObject:val];
}
-(NSArray *)yourStaticArray {
return yourStaticArray ;
}
#end
Well you need to have a property for that _currentTest if you want to be able to keep it around between method call.
Put this in your .h file
#property (nonatomic, copy) NSMutableArray * currentTest;
And this in hour .m file
- (NSMutableArray *)currentTest
{
if (!_currentTest)
_currentTest = [[NSMutableArray alloc] initWithCapacity:11];
return _currentTest;
}
- (void)keepCurrentArray:(id)object
{
[self.currentTest addObject:#"one"];
[self.currentTest addObject:#"two"];
[self.currentTest addObject:object];
NSLog(#"My Array is:%#", self.currentTest);
}
I Just try the code you've put on drop box and it's working exactly as it is suppose to, the array keeps it's value and everything,
BUT
Exactly as it is suppose to is not what you are trying to achieve
Your problem is not in AAA.m, your problem is in BBB.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
ViewController *kios = [ViewController new];
[kios keepCurrentArray:#"Test"];
[kios keepCurrentArray:#"Test2"];
}
I took the liberty of adding the #"test2" to the code you've send. If you run it you will see that your array still exist when the second call is made.
The REAL problem here is that you are creating a NEW ViewController each time. A brand new one, it is normal that it is empty (clean), it's a new one.
If I buy a note pad monday and fill it up, I don't expect when I'm buying an other one on friday to be already fill with the stuff I've wrote on monday in the previous one.
But this is exactly that behaviour that you are expecting from your ViewController.
You need to store your NSMutableArray in an other object that doesn't
get destroy and created over and over again.
This is happening because you are creating a new array every time that your method is called. Basically, you need to see if it has already been created, and only create it if needed. You can change your method to:
- (void)keepCurrentArray:(id)object
{
if (!_currentTest)
{
_currentTest=[[NSMutableArray alloc]init];
}
[_currentTest addObject:#"one"];
[_currentTest addObject:#"two"];
[_currentTest addObject:object];
NSLog(#"My Array is:%#",_currentTest);
}
EDIT:
In addition to the above problem, you also have this code which needs to be corrected (comments removed):
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
ViewController *kios = [ViewController new];
[kios keepCurrentArray:#"Test"];
}
This code creates a new instance of ViewController every time that you click on a row in the table. Because you are creating a new instance instead of reusing the old one, you start with an empty array each time. In order to keep adding to the same array, you need to keep using the same view controller.
In order to do this, you need to add a declared property to your .h file, similar to your currentTest declared property:
#property (strong,nonatomic) ViewController *kios;
Then, change your action so that you only create a new view controller if needed (the first time) and then reuses it after that:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (!_kios)
{
_kios = [ViewController new];
}
[_kios keepCurrentArray:#"Test"];
}

How to passing a NSMutableArray to another ViewController class

I have created NSMutale Array in "HeroListViewController". I want use it in another viewController which is MapTutorialViewController. I tried like this.
in HeroListViewController.h
MapTutorialViewController *maptutorialcontroller;
NSMutableArray *listData;
set properties and synthesize them correctly
in HeroListViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
listData = [[NSMutableArray alloc] init];
}
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *HeroTableViewCell = #"HeroTableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HeroTableViewCell];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:HeroTableViewCell] autorelease];
}
NSManagedObject *oneHero = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSInteger tab = [tabBar.items indexOfObject:tabBar.selectedItem];
switch (tab) {
case kByName:
cell.textLabel.text = [oneHero valueForKey:#"name"];
cell.detailTextLabel.text = [oneHero valueForKey:#"secretIdentity"];
break;
case kBySecretIdentity:
cell.detailTextLabel.text = [oneHero valueForKey:#"name"];
cell.textLabel.text = [oneHero valueForKey:#"secretIdentity"];
default:
break;
}
[listData addObject: [oneHero valueForKey:#"secretIdentity"]];
count=[listData count];
printf("No of items of listData:%u\n", count);
if(maptutorialcontroller==nil){
maptutorialcontroller= [[MapTutorialViewController alloc]initWithNibName:#"MapTutorialViewController" bundle:nil];
maptutorialcontroller.secondarray=listData;
}
count=[maptutorialcontroller.secondarray count];
printf("No of items of seconarray :%u\n", count);
return cell;
}
OUTPUTS : No of items of listData:3
No of items of seconarray :3 // both are correct
BUT the the problem I have, when I try to use the secondarray in "MapTutorialViewController" like this,
in MapTutorialViewController.h
HeroListViewController *heroviewcontroller;
NSMutableArray *secondarray;
set properties and synthesize them correctly
in MapTutorialViewController.m
- (void)viewDidLoad
{
heroviewcontroller = [[HeroListViewController alloc]initWithNibName:#"HeroListViewController" bundle:nil];
self.secondarray=[heroviewcontroller.listData mutableCopy];
//secondarray= heroviewcontroller.listData;
int count;
count = [secondarray count];
//
printf("No of items of secondarray from MapTutorialViewContriller :%u\n", count);
}
OUTPUT : No of items of secondarray from MapTutorialViewContriller :0
Why it is 0
whats the wrong with my code, please help me
Example
firstviewcontroller .h file
before #interface
use #class secondViewcontroller;
declare this inside of #interface with
secondViewcontroller *sVC;
then in firstViewController.m file
before #implementation
#import "secondViewcontroller.h"
then
-------------------
secondVC.h file
#interface inside declare this
say NSMutableArray *secondarray;
and sythasize them.
-------------------
after this
in firstViewcontroller.h viewdidload create this sVC by alloc and initwithnibname then
sVC.secondArray=urfirstArray;
now while u push this sVC controller to navigation controller u can nslog this array in viewdidload.
This would only work if you create and fill the mutable array in the init method.
You should look into delegation and/or notification.
How is that array being created within HeroListViewController? In this method, you are creating a NEW instance of HeroListViewController and trying to get a property from it. If you already have a HeroListViewController in memory, this is completely wrong.
Make a property on the class for this viewDidLoad method. It should be of type NSMutableArray. When you allocate and initialize this class, call [set myArray:heroListArray] on it from HeroListViewController. That should give you access to it.
I'm assuming that you have a view containing this new view and the hero list view. If that is the case, then you could create a property in the new view like so:
#property (nonatomic,retain)HeroListViewController *heroListViewController;
and then set it equal to the heroList from the outside:
newView.heroListViewController = HeroListViewController;
The main problem with your code at the moment is that you're creating a new instance of HeroListViewController by using alloc init, and you're not accessing the same thing. By setting the new view's heroListViewController property, you can get access to the correct viewController.
Finally, in viewDidLoad of the new view - I'd actually put the code in viewWillAppear:(BOOL)Animated - you can put code to match the arrays.
Note that this whole way of doing it is messy and could be better done with a singleton class if you need access to an array in multiple places. The above will help you get it working quick, but if you want a really clean fix, go here: http://www.iphonedevsdk.com/forum/iphone-sdk-tutorials/24135-singleton-classes.html

setting UITableViewCell to value from custom object instance

So basically I am trying to create instances of the class below every time I received a valid response from a web request and then store those instances in an array so I can access their data later. Then, I try to populate a table view with specific fields from the instance(s) that are stored in the array. I've been having some issues since I am very familiar with C++ and do this sort of thing with vectors and then just access based off of the index I need, but this has had me pulling my hair out! Thanks, code is below:
eventDetails.h:
#interface eventDetails : NSObject {
NSString *eventName, *eventID;
}
-(void) setEventID : (NSString *) ID;
-(void) setEventName: (NSString *) name;
-(NSString *) getEventName;
-(NSString *) getEventID;
and also note that
NSMutableArray *events
is declared in my .h file and
events = [[NSMutableArray alloc] init];
has been called in the viewDidLoad
I then dynamically create instances as a response is received from an web request and add them to an array:
if ([elementName isEqualToString:#"id"])
{
NSLog(#"at beginning of event, length is %i", [events count]);
temp = [[eventDetails alloc] init];
[temp setEventID:[NSMutableString stringWithString:soapResults]];
[soapResults setString:#""];
elementFound = FALSE;
}
if ([elementName isEqualToString:#"name"])
{
[temp setEventName:[NSMutableString stringWithString:soapResults]];
[events addObject:temp];
[soapResults setString:#""];
elementFound = FALSE;
//[temp release];
}
After everything is all said and done, I created a little test function to ensure the data was set correctly:
-(void) test{
for (eventDetails *s in events){
NSLog(#"Entry ID: %# with name %#", [s getEventID], [s getEventName]);
}
}
and I get the following (correct) output:
2011-04-09 18:53:24.624 Validator[90982:207] Entry ID: 701 with name iPhone Test Event
2011-04-09 18:53:24.625 Validator[90982:207] Entry ID: 784 with name Another iPhone Test Event
2011-04-09 18:53:24.626 Validator[90982:207] Entry ID: 839 with name third iphone
I then try to refresh the table view, and have it pull in data from the instances in the array:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
//---try to get a reusable cell---
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//---create new cell if no reusable cell is available---
if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
//---set the text to display for the cell---
eventDetails *cellDetails = [[eventDetails alloc] init];
NSInteger row = [indexPath row];
cellDetails = [[self events] objectAtIndex:row];
NSString *cellValue = [cellDetails getEventName];
NSLog(#"Event is: %#", cellValue);
cell.textLabel.text = cellValue;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
return cell;
}
But every time the program gets to this part, it crashed which a EXC_BAD_ACCESS where I say:
cell.textLabel.text = cellValue;
Thanks for your help. I think I might be doing something wrong with how I declare the instances of the eventDetails class, but I am not sure since it is working correctly as far as storing that data. If you need any more code, I have the missing sections.
There are too many omitted details in the code you posted to know for sure, but my guess would be the eventName isn't retained, and is deallocated sometime before you attempt to use it.
Check your setEventName: implementation; it would need to send either retain or copy to the name argument to ensure that the string won't be deallocated before you're done using it. However, the situation is more complex than that if you want to avoid memory leaks, so you if you haven't done so already, I'd recommend reading up on memory management, in particular, Apple's excellent Memory Management Programming Guide. (Note: I've given up posting links since Apple keeps changing them).
A side note: don't prefix the names of accessor methods with the word get; that would be fine in Java or C++, but this is Objective-C. Your accessors should look like this:
- (NSString *)eventName;
- (NSString *)eventID;
There's no guarantee that Foundation mechanisms that rely on introspection will work correctly with accessors that don't follow the documented naming conventions, so that's another thing to read up on. :-)