How can I pass the event to the toDoArray? I'm not sure what I'm missing. Any help appreciated.
SDEventModel.h
#interface SDEventModel : AWSDynamoDBObjectModel <AWSDynamoDBModeling>
ViewController.h
#property (nonatomic, strong) NSArray *toDoArray;
ViewController.m
if (task.result) {
AWSDynamoDBPaginatedOutput *paginatedOutput = task.result;
for (SDEventModel *event in paginatedOutput.items) {
//Do something with event.
NSLog(#"Task results: %#", event);
[self.toDoArray arrayByAddingObject:event];
NSLog(#"To do array results: %#", self.toDoArray);
[self.tableview reloadData];
}
}
Here is the output of the NSLog.
Task results: <SDEventModel: 0x7faa88d81430> {
city = "New York";
image = "photo-22.jpg";
title = "Hang with friends";
}
To do array results: (null)
The arrayByAddingObject method returns another array with the added object, and does not append the same.
This is how the method is intended to be used:
self.toDoArray = [self.toDoArray arrayByAddingObject:event];
However, in your case, it seems that the array is not even initialized. So you need to do something like this as well:
-(void) viewDidLoad {
[super viewDidLoad];
self.toDoArray = #[];
}
Define toDoArray as NSMutableArray like this in ViewController.h
#property (nonatomic, strong) NSMutableArray *toDoArray;
Now in ViewController.m initialise that array and add objects of event into it
if (task.result) {
self.toDoArray = [NSMutableArray new];
AWSDynamoDBPaginatedOutput *paginatedOutput = task.result;
for (SDEventModel *event in paginatedOutput.items) {
//Do something with event.
NSLog(#"Task results: %#", event);
[self.toDoArray addObject:event];
}
NSLog(#"To do array results: %#", self.toDoArray);
[self.tableview reloadData];
}
Please check Whether the Array in which you are adding object is Mutable or not?
if it is not mutable, you can create a new array or convert existing array to Mutable Array using mutableCopy
Related
I have two array, called array1 and array2. I would like to remove every object from array1 that's value of the "nameId" key can be find in both array. Actually I'm trying it in a for loop, but it doesn't make sense. It doesn not crash, it just simply calls the log in the else statement, that I don't understand why happens. Maybe somebody could show me the right solution.
NSMutableArray *newArray = [self.array1 mutableCopy];
for (PFObject * object in newArray) {
PFObject *placeholderObject = object;
for (PFObject *object2 in self.array2) {
if ([placeholderObject[#"nameId"] isEqualToString:object2[#"nameId"]]) {
[self.array1 removeObject:object];
NSLog (#"EXISTING OBJECT FOUND %#", object);
} else {
NSLog(#"UNIQUE OBJECT FOUND %#", idO[#"hirCime"]);
}
}
}
When creating a mutableCopy of an array you create a new array with a copy of every object in it but they aren't the same ones, so object is a member of newArray but is not a member of self.array1 so you can't remove it from that array.
This should work:
// Creates a new empty mutable array
NSMutableArray *newArray = [#[] mutableCopy];
for (PFObject *object in self.array) {
BOOL found = NO;
for (PFObject *object2 in self.array2) {
if ([object[#"nameId"] isEqualToString:object2[#"nameId"]]) {
found = YES;
NSLog (#"EXISTING OBJECT FOUND %#", object);
break;
} else {
NSLog(#"UNIQUE OBJECT FOUND %#", idO[#"hirCime"]);
}
}
if (!found) {
[newArray addObject:[object copy]];
}
}
// And maybe you want this
self.array = newArray;
I am trying to get my app working on WatchKit. I use Parse, and want to simply show the value of "Request" in my PFObject as a row in a WatchKit Table. I have the table and row set up and the row NSObject class simply has 1 label in it, where the "Request" field will populate. Here is what I have in my InterfaceController for the Watch.
#import "InterfaceController.h"
#import "TheTable.h"
#import <Parse/Parse.h>
#import "BlogView.h"
#interface InterfaceController()
#property (nonatomic, retain) PFObject *theObject;
#property (nonatomic, retain) NSMutableArray *rowTypesList;
#end
#implementation InterfaceController
- (void)awakeWithContext:(id)context {
[Parse setApplicationId:#"MYID"
clientKey:#"MYKEY"];
[super awakeWithContext:context];
// Configure interface objects here.
}
- (void)willActivate
{
PFQuery *query = [PFQuery queryWithClassName:#"Prayers"];
// If no objects are loaded in memory, we look to the cache first to fill the table
// and then subsequently do a query against the network.
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
NSArray *array = [objects objectAtIndex:0];//Selects the first "object" from all the "objects"
array = [array valueForKey:#"Request"];//Makes a NSArray from the "pairs" values
_rowTypesList = [array mutableCopy];//Converts the array to a NSMutableArray
NSLog(#"%#", _rowTypesList);
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}]; [self setupTable];
}
- (void)setupTable
{
NSLog(#"%#", _rowTypesList);
[_theActualTable setRowTypes:_rowTypesList];
for (NSInteger i = 0;_theActualTable.numberOfRows; i++)
{
NSObject *row = [_theActualTable rowControllerAtIndex:i];
TheTable *importantRow = (TheTable *) row;
[importantRow.textRowLabel setText:???]; //THIS IS PROBLEM AREA, HOW DO I GET TEXT HERE FROM THE MUTABLEARRAY
}
}
#end
How do I get the value from the array for that row into the label?
I don't understand Objective C that much, but I get an idea.
You need to either call setupTable from the ParseQuery callback and pass it the results array, or either iterate that array in the callback and in each iteration call mytable.label.setText(array[i]["property"])
Hope it makes sense.
I´m working on a class which retrieves links of a youtube playlist by using the YouTube Objective-C API.
Each URL is stored as a String strURL in an array called arrayURL, (for now) arrayURL is finally stored in arrayFinal, which I want to access from a different class.
Within the function I get the information I want (NSLog(#"%#", self.arrayFinal);). But when calling the function for example from another class (e.g. ViewController) I will always get an empty array back.
ViewController.m
YTDataHandler *youtubeObj = [YTDataHandler new];
[youtubeObj initYoutubeArray];
NSLog(#"%#", [youtubeObj arrayFinal]);
YTDataHandler.h
#import <Foundation/Foundation.h>
#interface YTDataHandler : NSObject
{
NSMutableArray *arrayFinal;
}
- (void)initYoutubeArray;
- (void)getYoutubeContent;
#property (nonatomic, retain) NSMutableArray *arrayFinal;
#end
YTDataHandler.m
#import "YTDataHandler.h"
#import "GTLServiceYouTube.h"
#import "GTLYouTube.h"
#import "GTLYouTubePlaylistSnippet.h"
#import "GTLYouTubeResourceId.h"
#implementation YTDataHandler
#synthesize arrayFinal;
- (void)initYoutubeArray {
self.arrayFinal = [[NSMutableArray alloc] init];
[self getYoutubeContent];
}
- (void)getYoutubeContent {
NSMutableArray *arrayURL = [[NSMutableArray alloc] init];
// Create a service object for executing queries
GTLServiceYouTube *service = [[GTLServiceYouTube alloc] init];
// API key
service.APIKey = #"YOUR_API_KEY";
// Create a query
GTLQueryYouTube *query = [GTLQueryYouTube queryForPlaylistItemsListWithPart : #"id, snippet, contentDetails"];
query.playlistId = #"UUa0XHGDbBL8re8UgO-OWNPA";
query.maxResults = 20;
query.type = #"video";
// Execute the query
GTLServiceTicket *ticket = [service executeQuery : query
completionHandler : ^(GTLServiceTicket *ticket, id object, NSError *error) {
// This callback block is run when the fetch completes
if (error == nil) {
GTLYouTubePlaylistItemListResponse *items = object;
// iteration of items and subscript access to items.
for (GTLYouTubePlaylistItem *item in items) {
// IDs of videos
NSString *strVideoId = [item.snippet.resourceId JSONValueForKey : #"videoId"];
// encode and extend the videoId, result as an URL
NSString *strEncoded = [strVideoId stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding];
NSString *strURL = [NSString stringWithFormat:#"http://www.youtube.com/watch?v=%#", strEncoded];
// store strURL
[arrayURL addObject : (#"%#", strURL)];
}
// finally store arrayURL
[self.arrayFinal addObject : (#"%#", arrayURL)];
NSLog(#"%#", self.arrayFinal);
} else {
NSLog(#"Error: %#", error);
}
}];
}
#end
What am I doing wrong in the // Execute the query-part?
In your view controller, when you make the call to getYoutubeContent on your YTDataHandler instance, you cannot expect the array to be immediately populated. It will be eventually populated when the query executes and the handler code is executed. In your handler code it always works because you are in the same thread, and you use arrayFinal when it is ready. In your view controller you need to wait until the array is ready, before you start using it. E.g. you could set a boolean flag on your YTDataHandler which your view controller can register a key-value observing callback (KVO), so that you can get automatically notified when the array is ready.
ps.
Why don't you use:
[arrayURL addObject: strURL];
instead of:
[arrayURL addObject : (#"%#", strURL)];
?
So I have this method in which I query some Singleton class to get data, I add it to my mutable array called profile details, but It doesn't get added, if i add it to a temp array first and then use that to assign it to my profile details array it works? What's happening here?
//Property declaration
#property (nonatomic, strong) NSMutableArray *profileDetails;
//Method definition
- (void) getAllProfiles : (NSArray *) profiles
{
if (_myHealthDetailService == nil) {
self.myHealthDetailService = [[MyHealthDetailService alloc] init];
}
if (profiles) {
if (self.currentProfileCounter < [profiles count]) {
MyHealth *profile = [profiles objectAtIndex:self.currentProfileCounter];
[self.myHealthDetailService requestForMyHealthDetailWithHealth:profile completion:^(NSArray *healths) {
self.currentProfileCounter = self.currentProfileCounter + 1;
if (healths) {
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:healths.count];
for (MyHealth *profile in healths) {
NSLog(#"Adding Proile: %#",profile);
[self.profileDetails addObject:profile];
[tempArray addObject:profile];
NSLog(#"Proile details array after adding %# profile is: %#",profile, self.profileDetails);
NSLog(#"Temp Proile details array after adding %# profile is: %#",profile, tempArray);
}
self.profileDetails = tempArray;
NSLog(#"Proile details array after copying is: %#",self.profileDetails);
}
DashboardHealthCell_iPad *cell = (DashboardHealthCell_iPad *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:DashboardRow_iPadTypeHealth inSection:0]];
NSLog(#"Proile details array is: %#",self.profileDetails);
[cell populateMyHealthProfiles:self.profileDetails];
} failureBlock:^(NSError *error) {
}];
}
}
}
Relevant NSLog output:
2014-03-12 12:45:58.144 CHM[9768:70b] Proile details array after adding <MyHealth: 0xd562ce0> profile is: (null)
2014-03-12 12:45:58.144 CHM[9768:70b] Temp Proile details array after adding <MyHealth: 0xd562ce0> profile is: (
"<MyHealth: 0xd562270>",
"<MyHealth: 0xd5629e0>",
"<MyHealth: 0xd562ce0>"
)
2014-03-12 12:45:58.144 CHM[9768:70b] Proile details array after copying is: (
"<MyHealth: 0xd562270>",
"<MyHealth: 0xd5629e0>",
"<MyHealth: 0xd562ce0>"
)
The problem seems to be that self.profileDetails is nil by the time you invoke
[self.profileDetails addObject:profile];
There's no place where you alloc / init that Array, so nothing gets added. You can probably get rid of your tempArray by doing
// this
profileDetails = [NSMutableArray arrayWithCapacity:healths.count];
// instead of this
NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:healths.count];
I am making a NSObjectClass that has a method in it that returns self.
This is what it looks like roughtly
storageclass.h
// storageclass vars go here
- (storageclass)assignData:(NSDictionary *)dictionary;
storageclass.m
//#synthesise everything
- (storageclass)assignData:(NSDictionary *)dictionary {
//assign values from dictionary to correct var types (i.e. NSString, Int, BOOL)
//example
Side = [dictionary valueForKey:#"Side"];
return self;
}
Then what I want to do is use this class by passing a NSDictionary var through its method to return a object of type storageclass that I can then use to access the vars using dot notation.
this is how I am trying to access this class at the moment
accessorViewController.h
storageclass *store;
#property (strong, nonatomic) storageclass *store;
accessorViewController.m
#synthesize store;
- (void)getstoreready {
[store assignData:someDictionary];
nslog(#"%#", store);
}
this NSLog returns nothing and in the debugger all of stores class vars are empty showing nothing has been assigned. I am 100% positive the dictionary vars being used in the assignData method have the correct valueForKey values.
I think it has something to do with how I am using it here [store assignData:someDictionary]; how do i catch the turned data so I can use it?
any help would be appreciated.
The store object is never initialized so it will be nil thats obvious isn't it. Initialize the store object first, then call its instance methods onto it. And by doing that, you'll have a storageclass object which is properly assigned with some dictionary already.
And if you want to have a storageclass object like your code shows, you should make your (storageclass)assignData:(NSDictionary *)dictionary method a class method instead of an instance method by putting a + sign
+(storageclass*)assignData:(NSDictionary *)dictionary;
Then properly initialize it and assign the data (dictionary to variables) accordingly and return it to the caller. For example :-
in .m file
+(storageclass*)assignData:(NSDictionary *)dictionary{
storageclass *test = [[storageclass alloc] init];
if (test) {
test.someDict = dictionary;
}
return test;
}
Then use this class method in your view controller as
- (void)getstoreready {
store = [storageClass assignData:someDictionary];
nslog(#"%#", store);
}
Also Do follow the naming convention for classes and instances. A class's name must start with a capital letter only and the opposite for any class instances.
In User.h
#interface User : NSObject
#property (nonatomic, copy) NSString *name;
- (id)initWithDictionary:(NSDictionary *)dictionary;
+ (NSArray *)usersFromArray:(NSArray *)array;
#end
In User.m
- (id)initWithDictionary:(NSDictionary *)dictionary
{
self = [super init];
if (self) {
if (dictionary)
{
self.name = dictionary[#"kUserName"];
}
}
return self;
}
+ (NSArray *)usersFromArray:(NSArray *)array
{
NSMutableArray *users = [NSMutableArray array];
for (NSDictionary *dict in array) {
User *user = [[User alloc]initWithDictionary:dict];
[users addObject:user];
}
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"name"
ascending:YES];
return [users sortedArrayUsingDescriptors:#[descriptor]];
}
In ViewController.m
import "User.h"
self.currentArray = [User usersFromArray:array];