Passing NSString between views returns NULL - ios7

I am trying to return an NSString between views. Code below:
Data Source:
.h:
#property (nonatomic, strong) NSString *selectedDate;
.m:
#synthesise selectedDate;
-(NSDate *)date
{
NSInteger monthCount = [self.months count];
NSString *month = [self.months objectAtIndex:([self selectedRowInComponent:MONTH] % monthCount)];
NSInteger yearCount = [self.years count];
NSString *year = [self.years objectAtIndex:([self selectedRowInComponent:YEAR] % yearCount)];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:#"MMMM:yyyy"];
NSDate *date = [formatter dateFromString:[NSString stringWithFormat:#"%#:%#", month, year]];
selectedDate = [NSString stringWithFormat:#"%#", date];
return date;
}
Loading View:
.m:
[VIEWNAME] *firstviewObj=[[[VIEWNAME] alloc]init];
NSLog(#"%#",firstviewObj.selectedDate);
What is my issue??

Please do this
VIEWNAME *firstviewObj=[[VIEWName alloc]init];
NSDate *myDate = [firstviewobj date];
NSLog(#"%#",firstviewObj.selectedDate);
Remember myDate and firstviewObj.selectDate will give same result

Related

Parse PFObject ID to map annotation title & subtitle

I'm using the parse framework to collect objects in a class and display them on a map. Currently, the annotation titles display the "CreatedAt" string, and the subtitles display the "coordinates". How can I change the title and subtitle to another PFObject ID that I've set? I've based a lot of my code on the GeoLocations app that Parse have supplied. The code is as follows:
#interface GeoPointAnnotation()
#property (nonatomic, strong) PFObject *object;
#end
#implementation GeoPointAnnotation
- (id)initWithObject:(PFObject *)aObject {
self = [super init];
if (self) {
_object = aObject;
PFGeoPoint *geoPoint = self.object[#"coordinates"];
[self setGeoPoint:geoPoint];
}
return self;
}
- (void)setGeoPoint:(PFGeoPoint *)geoPoint {
_coordinate = CLLocationCoordinate2DMake(geoPoint.latitude, geoPoint.longitude);
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.timeStyle = NSDateFormatterMediumStyle;
dateFormatter.dateStyle = NSDateFormatterMediumStyle;
}
static NSNumberFormatter *numberFormatter = nil;
if (numberFormatter == nil) {
numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
numberFormatter.maximumFractionDigits = 3;
}
_title = [dateFormatter stringForObjectValue:self.object.createdAt];
_subtitle = [NSString stringWithFormat:#"%#, %#", [numberFormatter stringFromNumber:[NSNumber numberWithDouble:geoPoint.latitude]],
[numberFormatter stringFromNumber:[NSNumber numberWithDouble:geoPoint.longitude]]];
}
#end
Fixed it by replacing some of the code with this:
static NSString *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSString alloc] init];
}
and then this:
_title = [dateFormatter stringByAppendingString:self.object[#"Name"]];
_subtitle = [dateFormatter stringByAppendingString:self.object[#"Location"]];

Getting the date of an NSDate date from within a category

I add a category to NSDate as follows:
#interface NSDate (ElapsedDays)
-(unsigned long) elapsedDays: (NSDate *) theDate;
#end
#implementation NSDate (ElapsedDays)
-(unsigned long) elapsedDays:(NSDate *)theDate
{
self.[???]
}
#end
In main, I declare NSDate as follows:
NSDate *today=[NSDate date];
Now in the elapsedDays implementation, how can I access the date that NSDate was initialized with?
The receiver of the message elapsedDays is self in the method implementation scope.
For example:
#import <Foundation/Foundation.h>
#interface NSDate (ElapsedDays)
- (NSInteger)elapsedDaysSinceDate:(NSDate *)theDate;
#end
#implementation NSDate (ElapsedDays)
static const NSInteger SecondsPerDay = 86400;
- (NSInteger)elapsedDaysSinceDate:(NSDate *)theDate {
NSTimeInterval interval = [self timeIntervalSinceDate:theDate];
return interval/SecondsPerDay;
}
#end
int main(int argc, char *argv[]) {
#autoreleasepool {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMddyyyy"];
NSDate *date1 = [dateFormatter dateFromString:#"01012012"];
NSDate *date2 = [dateFormatter dateFromString:#"12312012"];
printf("Date difference = %ld",[date2 elapsedDaysSinceDate:date1]);
}
}
Prints Date difference = 365 to the console.
EDIT (using Gregorian calendrical calculations)
#import <Foundation/Foundation.h>
#interface NSDate (ElapsedDays)
- (NSInteger)elapsedDaysSinceDate:(NSDate *)theDate;
#end
#implementation NSDate (ElapsedDays)
- (NSInteger)elapsedDaysSinceDate:(NSDate *)theDate {
NSTimeInterval interval = [self timeIntervalSinceDate:theDate];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSDayCalendarUnit
fromDate:theDate
toDate:self
options:0];
return [components day];
}
#end
int main(int argc, char *argv[]) {
#autoreleasepool {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMddyyyy"];
NSDate *date1 = [dateFormatter dateFromString:#"01012012"];
NSDate *date2 = [dateFormatter dateFromString:#"12312012"];
printf("Date difference = %ld",[date2 elapsedDaysSinceDate:date1]);
}
}

How to make a string from a NSDate variable as well as another NSString variable

I am playing around with making a unique ID for whenever a button is pushed in my application. I basically want it to be two NSString variables that I make concatenated together.
So far, what I have got it mostly working as it gives me no errors in the code itself, but it does only give me (null) as my text in my label.
Where I have the 2 is basically a placeholder for where I will eventually have a variable that will look up what is in the plist for the username.
My code for this is:
NSString *UserID;
NSDate *TimeNow;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMddhhmm"];
UserID = [NSString stringWithFormat:#"",'Username'];
NSString *CurrentTime = [dateFormatter stringFromDate:TimeNow];
SessionID = [NSString stringWithFormat:#"%# %#", UserID, CurrentTime];
UniqueSessionID.text = SessionID;
You haven't initialised TimeNow. And your UserID is just being set to the empty string. To clean up that code, I would do this:
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMddhhmm"];
NSString *CurrentTime = [dateFormatter stringFromDate:[NSDate date]];
NSString *SessionID = [NSString stringWithFormat:#"Username %#", CurrentTime];
UniqueSessionID.text = SessionID;
Update:
To have "Username" dynamic just do this:
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMddhhmm"];
NSString *CurrentTime = [dateFormatter stringFromDate:[NSDate date]];
NSString *UserID = #"Some user";
NSString *SessionID = [NSString stringWithFormat:#"%# %#", UserID, CurrentTime];
UniqueSessionID.text = SessionID;
Then just change UserID to what you want the username to be.
I think that there should be:
NSDate *TimeNow = [NSDate date];
NSDate *dateFromString = [[NSDate alloc] init];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy/MM/dd hh:mm"];//this is the date format of dateFromString
NSString *CurrentTime = [dateFormatter stringFromDate:TimeNow];
[dateFromString release];
UserID = [NSString stringWithFormat:#"",'Username'];
SessionID = [NSString stringWithFormat:#"%# %#", UserID, CurrentTime];
UniqueSessionID.text = SessionID;

Sort NSDictionaries in NSMutableArray by NSDate

I have a NSMutableArray with dictionaries, all of the dict's contain a NSDate is form of NSString with key 'Date'. I want to sort the NSDictionaries by the Dates. So for example i have the following state of the array:
Dict
Date
20.06.1996 23:30
Dict
Date
04.10.2011 19:00
Dict
Date
20.06.1956 23:39
And I want to sort it, so that it looks like this:
Dict
Date
20.06.1956 23:39
Dict
Date
20.06.1996 23:30
Dict
Date
04.10.2011 19:00
I have already experimented with NSSortDescriptor, but without success...
Update:
I have managed to sort the dates, but I came to this problem: In the dicts there is not only dates, also other objects, and what my code does is it only switches the date values between the dicts, instead of switching the complete dicts around. With this, the other values in the dicts get assigned a wrong date, which is very bad. Can anybody help me? Heres my code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"savedData.daf"];
NSMutableArray *d = [NSMutableArray arrayWithContentsOfFile:path];
for (int ii = 0; ii < [d count]; ii++) {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
if (is24h) {
[dateFormatter setDateFormat:#"dd.MM.yyyy HH:mm"];
}
else {
[dateFormatter setDateFormat:#"dd.MM.yyyy hh:mm a"];
}
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *dat = [dateFormatter dateFromString:[[d valueForKey:#"Date"] objectAtIndex:ii]];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[d objectAtIndex:ii];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:dat forKey:#"Date"];
[d replaceObjectAtIndex:ii withObject:newDict];
[newDict release];
}
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:#"Date" ascending:YES];
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];
[sorter release];
NSMutableArray *sorted = [NSMutableArray arrayWithArray:[d sortedArrayUsingDescriptors:sorters]];
[sorters release];
NSLog(#"%#",sorted);
for (int ii = 0; ii < [sorted count]; ii++) {
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
if (is24h) {
[dateFormatter setDateFormat:#"dd.MM.yyyy HH:mm"];
}
else {
[dateFormatter setDateFormat:#"dd.MM.yyyy hh:mm a"];
}
[dateFormatter setLocale:[NSLocale currentLocale]];
NSString *sr = [dateFormatter stringFromDate:[[sorted valueForKey:#"Date"] objectAtIndex:ii]];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[d objectAtIndex:ii];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:sr forKey:#"Date"];
[sorted replaceObjectAtIndex:ii withObject:newDict];
[newDict release];
}
NSLog(#"before: %#"
""
"after: %#",d,sorted);
[sorted writeToFile:path atomically:YES];
There are many ways to do this, one would be to use NSDate objects instead of NSStrings (or NSStrings formatted according to ISO 8601, so that the lexicographic sort would match the desired sorting). Then you could do:
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"Date"
ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObject:descriptor]];
Or, if you can't (or don't want to) change your data, you can always sort using a block:
[array sortUsingComparator:^(id dict1, id dict2) {
NSDate *date1 = // create NSDate from dict1's Date;
NSDate *date2 = // create NSDate from dict2's Date;
return [date1 compare:date2];
}];
Of course this would probably be slower than the first approach since you'll usually end up creating more than n NSDate objects.
There are a couple of options, one is to put NSDate objects in the dictionary.
One problem with comparing the strings is that you can 't just do a string compare because the year is not in the most significant potion of the string.
So, you will need to write a comparison method to use with:
- (NSArray *)sortedArrayUsingComparator:(NSComparator)cmptr
or perhaps:
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context
The comparator will need to handle the dd.mm.yyyy hh:mm string format.
Other options include adding another dictionary key with an NSDate representation and sorting on that.

objective-c cant find memory leak

im mapping an xml on a custom nsobject.
when the user hits reload the function is called again.
i get several memory leaks on all strings:
UPDATE this is the current code.
- (void)mapDataOnModel
{
if(mixesArr != nil)
{
//[mixesArr release];
[mixesArr removeAllObjects];
[playListArr removeAllObjects];
}
else
{
mixesArr = [[NSMutableArray alloc]init];
playListArr = [[NSMutableArray alloc] init];
}
MixVO *tmpMix;
AudioVO *tmpAudio;
for (DDXMLElement *node in nodes)
{
tmpMix = [[MixVO alloc] init];
tmpMix.uuid = [[node attributeForName:#"uuid"] stringValue];
tmpMix.name = [[[node elementsForName:#"name"] objectAtIndex:0] stringValue];
tmpMix.artist = [[[node elementsForName:#"artist"] objectAtIndex:0] stringValue];
tmpMix.path = [[[node elementsForName:#"file"] objectAtIndex:0] stringValue];
tmpMix.headline = [[[node elementsForName:#"headline"] objectAtIndex:0] stringValue];
tmpMix.teaser = [[[node elementsForName:#"teaser"] objectAtIndex:0] stringValue];
tmpMix.copy = [[[node elementsForName:#"copy"] objectAtIndex:0] stringValue];
tmpMix.isHighlight = NO;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"HH:mm:ss"];
tmpMix.duration = [dateFormat dateFromString:[[[node elementsForName:#"duration"] objectAtIndex:0] stringValue]] ;
[dateFormat release];
// CHECK IF IT IS A HIGHLIGHT MIX
for (int i = 0; i < [[highlightsNode elementsForName:#"member"] count]; i++)
{
NSString *highlightID;
highlightID = [[[highlightsNode elementsForName:#"member"] objectAtIndex:i] stringValue] ;
if([tmpMix.uuid isEqualToString:highlightID])
{
tmpMix.isHighlight = YES;
}
}
if([[node elementsForName:#"image_standard"] count] > 0)
tmpMix.image_standard = [[[node elementsForName:#"image_standard"] objectAtIndex:0] stringValue] ;
if([[node elementsForName:#"image_artist"] count] > 0)
tmpMix.image_artist = [[[node elementsForName:#"image_artist"] objectAtIndex:0] stringValue] ;
if([[node elementsForName:#"image_teaser"] count] > 0)
tmpMix.image_teaser = [[[node elementsForName:#"image_teaser"] objectAtIndex:0] stringValue] ;
if([[node elementsForName:#"image_player"] count] > 0)
tmpMix.image_player = [[[node elementsForName:#"image_player"] objectAtIndex:0] stringValue] ;
/*
tmpAudio = [[AudioVO alloc] init];
tmpAudio.file = tmpMix.path;
NSString *tmpDuration;
tmpDuration = [[[node elementsForName:#"duration"] objectAtIndex:0] stringValue];
tmpAudio.duration = tmpDuration;
// PARSE TRACKS
NSArray *track = NULL;
track = [node elementsForName:#"tracks"];
DDXMLElement *trackElems = [track objectAtIndex:0];
NSArray *tracks = NULL;
tracks = [trackElems elementsForName:#"track"];
NSMutableArray *tracksArray;
tracksArray = [[NSMutableArray alloc]init];
TrackVO *tmpTrack;
for (DDXMLElement *node2 in tracks)
{
tmpTrack = [[TrackVO alloc] init];
tmpTrack.timecode = [[node2 attributeForName:#"timecode"] stringValue];
tmpTrack.name = [node2 stringValue];
[tracksArray addObject:tmpTrack];
[tmpTrack release];
}
tmpAudio.tracksArr = tracksArray;
[tracksArray release];
tmpMix.audioVO = tmpAudio;
[tmpAudio release];
*/
[mixesArr addObject:tmpMix];
[tmpMix release];
}
// SORT PROGRAMM
/*
NSSortDescriptor *lastDescriptor =
[[[NSSortDescriptor alloc]
initWithKey:#"artist"
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray * descriptors =
[NSArray arrayWithObjects:lastDescriptor, nil];
NSArray * sortedArray = [mixesArr sortedArrayUsingDescriptors:descriptors];
//[mixesArr release];
mixesArr = [[NSMutableArray alloc]initWithArray:sortedArray];
// PARSE PLAYLIST
for (DDXMLElement *node in nodesPl)
{
SchedVO *tmpSched;
tmpSched = [[SchedVO alloc] init];
NSString *timeStr;
timeStr = [[node attributeForName:#"timestamp"] stringValue];
tmpSched.date = [NSDate dateWithTimeIntervalSince1970:timeStr.intValue];
tmpSched.uid = [node stringValue];
[playListArr addObject:tmpSched];
//[tmpSched release];
}
*/
[self updateDone];
}
MixVO:
#interface MixVO : NSObject
{
NSString *uuid;
NSString *name;
NSString *artist;
NSString *path;
NSString *headline;
NSString *teaser;
NSString *copy;
NSString *image_standard;
NSString *image_artist;
NSString *image_teaser;
NSString *image_player;
NSDate *duration;
AudioVO *audioVO;
BOOL isHighlight;
}
#property (nonatomic,retain) NSString *uuid;
#property (nonatomic,retain) NSString *name;
#property (nonatomic,retain) NSString *artist;
#property (nonatomic,retain) NSString *path;
#property (nonatomic,retain) NSString *headline;
#property (nonatomic,retain) NSString *teaser;
#property (nonatomic,retain) NSString *copy;
#property (nonatomic,retain) NSString *image_standard;
#property (nonatomic,retain) NSString *image_artist;
#property (nonatomic,retain) NSString *image_teaser;
#property (nonatomic,retain) NSString *image_player;
#property (nonatomic,retain) NSDate *duration;
#property (nonatomic,retain) AudioVO *audioVO;
#property BOOL isHighlight;
#end
maybe someone can help me with this.
thanks in advance
alex
if(mixesArr != nil)
{
[mixesArr removeAllObjects];
[playListArr removeAllObjects];
}
mixesArr = [[NSMutableArray alloc]init];
This suggest mixesArr could already be allocated, and you simply allocate a new instance, making the original mixesArr a dangling pointer.
Shouldn't you write something like:
if(mixesArr != nil)
{
[mixesArr removeAllObjects];
[playListArr removeAllObjects];
}
else {
mixesArr = [[NSMutableArray alloc]init];
}
Or something similar?
Where are you releasing mixesArr?
You'll also want to release all the strings you're retaining.