I am developing an application, in which I am getting the values from the URL, for example, take it as (demo.png), here what I am doing is, i am separating the string with <componentsSeparatedByString:#"." > and saving that in the array (Index 0 : demo & Index 1: png ). And, it works fine. Now, what i getting struck here, when the value from the URL doesn't contain ".png, .jpeg" then error message is coming. How can i check whether there is a value in ObjectAtIndex:1 is null. What i did for this was,
Coding :
if ([array45 objectAtIndex:1] == NSNULL NULL) {
NSLog(#"object at index %i has no data", i);
}
Error message:
[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
Help me with your valuable solutions.
NSArray *aray = [#"demo.png" componentsSeparatedByString:#"."];
if ([[aray lastObject] isEqualToString:#"png"])
{
NSLog(#"There is an image with .png");
}
else {
NSLog(#"There is no image eith .png extension");
}
First you want to find out how many objects are in the array.
int count = [array count];
If you don't have the correct count you don't check what's in an index.
Related
I have 2 NSMutableArrays and i want to put certain object form 1 array to the other array I have already code written but it doesnt work and it gives me this error:
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 296 beyond bounds [0 .. 295]'
* First throw call stack:
(0x1c9a012 0x10d7e7e 0x1c3c0b4 0x2f04 0xb20b90 0x1c59376 0x1c58e06 0x1c40a82 0x1c3ff44 0x1c3fe1b 0x1bf47e3 0x1bf4668 0x1f65c 0x252d 0x2455)
libc++abi.dylib: terminate called throwing an exception
Initialisierung in viewdidload:
arrayLine1 =[[NSMutableArray alloc] initWithCapacity:80000];
arrayLine1a =[[NSMutableArray alloc] initWithCapacity:70000];
line1tagzahl=0;
line1tagzahl2=0;
passing code:
for (int a=0; a<10; ) {
[arrayLine1a insertObject:[arrayLine1 objectAtIndex:line1tagzahl2] atIndex:line1tagzahl2];
line1tagzahl2=line1tagzahl2+1;
a=a+1;
}
function to create objects in array(this function is called very fast and frequently) :
for (float a=0; a<0.8; ) {
UIImageView *line1 =[[UIImageView alloc] initWithFrame:CGRectMake(Startpoint1.center.x-(w/2),Startpoint1.center.y-kurve1yf+a,w,h)];
line1.image=[UIImage imageNamed:#"Unbenannt"];
line1.tag=line1tagzahl;
[self.view addSubview:line1];
[arrayLine1 insertObject:line1 atIndex:line1tagzahl];
line1tagzahl=line1tagzahl+1;
a=a+0.1;
}
now you should have more information
and if you ask i have more than 10 objects in array2
Seems you haven't read the error message you posted. You have 296 objects in the array. But if you just want to copy the array, why don't you... er... copy it?
NSMutableArray *secondArray = [firstArray mutableCopy];
Is there any problem with using a default method -addObjectsFromArray: of NSMutableArray class?
- (void)serverGotResponse:(NSArray *)objects {
[_myMutableArray addObjectsFromArray:objects];
}
To prevent out of bounds exception, you should use count property:
while (i < array.count) {
// do something ..
i++;
}
if you are copying all the objects, you can just copy the entire array:
array2 = [array1 copy]
You are trying to add the first 10 objects, but your exception was thrown on index 296, which is the first index that comes out of bounds.
For some reason, your while condition is not working properly, so I suggest you start looking there
I also suggest you use a for, it's actually more simple and straightforward than a potential infinite loop
for (int a = 0; a < 10; a++) {
[array1 insertObject:[array2 objectAtIndex:a] atIndex:a];
}
I'm just starting out with objective c (coming from java) and I'm working on a calculator program just to practice with the syntax and some basic stuff. The way I'm going about it is having the user input a string and looking through for operators (taking order of operations into account) and then finding the term surrounding that operator, calculating it, replacing the term with the answer, and repeating for all the terms; however, I'm having an issue with the method I'm using to calculate the term. I pass in the index of the operator and have it loop backwards until it hits another operator to find the number immediately before it, and do the same forwards for the number after. My issue is that the loop does not stop when it hits the operators, and instead just continues until the end of the string in both directions. It's probably something really simple that I've overlooked but I've been trying to figure this out for a while and can' seem to get it. I've included an SSCCE of just the first half of the method, with a predetermined string and operator index. (also, a secondary question: is there any better way to post code blocks on this site rather than manually putting in 4 spaces before every line?)
#import <Foundation/Foundation.h>
int firstNumInTerm(int index);
NSString *calculation;
int main(int argc, const char * argv[])
{
#autoreleasepool {
calculation = #"51-43+378*32";
int firstNumber = firstNumInTerm(9);
NSLog(#"The number before the term is: %i", firstNumber);
}
return 0;
}
int firstNumInTerm(int index){
int firstNumIndex = index - 1;
int firstNumLength = 1;
NSRange prevChar = NSMakeRange(firstNumIndex - 1, 1);
while ([calculation substringWithRange:prevChar] != #"*" &&
[calculation substringWithRange:prevChar] != #"/" &&
[calculation substringWithRange:prevChar] != #"+" &&
[calculation substringWithRange:prevChar] != #"-" &&
firstNumIndex > 0) {
NSLog(#"prevChar: %#", [calculation substringWithRange:prevChar]);//TEST
firstNumIndex--; firstNumLength++;
prevChar = NSMakeRange(firstNumIndex - 1, 1);
}
NSRange firstRange = NSMakeRange(firstNumIndex, firstNumLength);
int firstNum = [[calculation substringWithRange:firstRange] intValue];
NSLog(#"firstNum String: %#", [calculation substringWithRange:firstRange]);//TEST
NSLog(#"firstNum int: %i", firstNum);//TEST
return firstNum;
}
The problem with this line:
[calculation substringWithRange:prevChar] != #"*" is that you are comparing the value of two pointers. [calculation substringWithRange:prevChar] returns a pointer to an NSString object, as does the NSString literal statement #"*". The simplest way to compare two strings is by using the isEqualToString: method of NSString. For example:
NSString *myName = #"Stephen";
NSString *yourName = #"Matt";
if([myName isEqualToString:yourName]){
printf("We have the same name!");
}
else{
printf("We do not have the same name");
}
If you are going to be doing a lot of string comparisons, it might be wise to write a macro, such as:
#define STREQ(x,y) [x isEqualToString:y]
Regarding copy/pasting code into StackOverflow:
Since I use XCode 99% of the time, I find it handy to select the text I am going to copy and then hit Cmd-]. This shifts the text to the right one tab-width. I then Cmd-c to copy and then Cmd-[ to undo the right-shift.
You can't do that in Objective-C: [calculation substringWithRange:prevChar] != #"*"
Instead, you need to do :
[[calculation substringWithRange:prevChar] compare:#"*"] != NSOrderedSame
(I know, it's longer, but arithmetic operators aren't overloaded for string like they are in Java).
I see others have answered this to correct the issue with your string comparison operations, but a better way to split this string up would be using NSString's native parsing methods. For example:
NSArray *numbers = [ calculation componentsSeparatedByCharactersInSet:
[ NSCharacterSet characterSetWithCharactersInString: #"*/+-" ] ];
Will give you an array containing each of the numbers (in order) in your string. You could come up with custom parsing routines, but using NSString's is going to likely be more straightforward and a lot less buggy. It will also be easier for someone else to read and understand.
while((![[calculation substringWithRange:prevChar] isEqualToString:#"*"]) && …){
}
or
NSArray *operators = #[#"+", #"-", #"*", #"/"];
while(![operators contains:[calculation substringWithRange:prevChar]])
I am getting some unexpected behavior with CoreData and NSPredicate. In a large database population I have different Managed Objects relating to one-another. However, I have a problem with the following. When giving an id (NSNumber, given as NSString to this function) I don't get a result unless I save the whole context first. I don;t want to do that as it takes too much time (as it is a large set of data). The code is:
- (DOSite *) findSite:(NSString *) siteId {
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"(id = %#)", siteId];
[NSFetchedResultsController deleteCacheWithName:nil];
[[self fetchedResultsController].fetchRequest setPredicate:predicate];
NSError *fetchError;
if (![[self fetchedResultsController] performFetch:&fetchError]) {
// Handle the error.
// This is a serious error and should advise the user to restart the application
NSLog(#"Fetching data error: %#", [fetchError localizedDescription]);
}
if([[[self fetchedResultsController] fetchedObjects] count] == 0){
return NULL;
}
return (DOSite *)[[[self fetchedResultsController] fetchedObjects] objectAtIndex:0];
}
So when I add an x number of items (using +[NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:]) doing a search on all items return the right amount of items.
When searching for a string (e.g.predicateWithFormat:#"(name LIKE %#)") I get positive results, but when using the above code predicateWithFormat:#"(id = %#) I get zero results.
The only way I can get results is to save the whole context and then perform the fetchRequest, then suddenly it works.
So there must be something small I do wrong in searching for the id, I just seem to be blind to find it and spend two days at it now to narrow it down to this point. Is there anybody who can give me some advice on this?
This may not work, but have you tried using a name more complex than "id" in your entity (like "SiteID")? Sometimes very short names overlap with other system properties and it causes odd issues.
The problem was that I gave a NSString to the predicate as outlined above. When changing that to an int (ie predicateWithFormat:#"(id == %i)") it works fine for some reason.
I have an NSDictionary that looks kind of like this:
list
{{
-> id
-> name
-> color
},
{
-> id
-> name
-> color
}}
which works great when I loop through it! But unfortunately, sometimes, the structure looks like this:
list {
-> id
-> name
-> color
}
Where there's only one result returned. So I need to know if there's one or if there's more than one result returned.
I tried checking for the number of results by seeing if the ID key exists in "list" but unfortunately when I do valueForKey I get back something like this for multiple results: (429, 24) and just 429 if there's only one result.
But I can't do a count on the 429 value obviously.
Here's one of the things I was trying to do, which works great for multiple results, but not if there's one.
NSInteger numResults = [[list valueForKeyPath:#"id.#count"] intValue];
Any idea how to find out if it's an set of results or just a single result? I don't have any control over the data as it comes from a JSON object via a web service.
I also tried using [list mutableArrayValueForKey:#"id"]; and that seems to still only return an array if there's more than one result. I assumed I'd get back an array with one element if there was only one element...but apparently not?
You can check which kind of object you are dealing with using isKindOfClass:
NSInteger numResults = 1;
if ([list isKindOfClass:[NSArray class]]) {
numResults = [list count];
}
If I understand correctly, one result will actually give you an NSDictionary, but multiple results will give you an NSArray of NSDictionaries?
Assuming that is the case, you could check the type of object you have like this:
if ([list isKindOfClass:[NSDictionary class]]) {
// Must be single result
}
else {
// Multiple results case
}
Otherwise, if I've misunderstood, perhaps you could clarify.
I'm having a problem with relationships between to entities in Core Data. I'm parsing some JSON and adding the entities:
if ([hourSets isKindOfClass:[NSArray class]]) { // check to see that we have got some hours back
for (NSDictionary *hourSet in hourSets) {
Hourset *thisHourSet = (Hourset *)[NSEntityDescription
insertNewObjectForEntityForName:#"Hourset"
inManagedObjectContext:managedObjectContext];
[thisHourSet setStartDate:[hourSet objectForKey:#"start_date"]];
[thisHourSet setEndDate:[hourSet objectForKey:#"end_date"]];
[record addHoursetsObject:thisHourSet];
}
}
...and then later trying to grab them again:
NSSet *hourSets = [self.listing valueForKeyPath:#"hoursets.hourset"];
NSLog(#"There are %# hourSets", [hourSets count]);
I'm getting Program received signal: “EXC_BAD_ACCESS”. when trying to access that hourSets NSSet in any way, including just counting the items in it.
Any suggestions? Pretty stumped. Thanks!
I am inferring your entity graph here but:
[self.listing valueForKeyPath:#"hoursets.hourset"]
... translates to a keypath of listing.hoursets.hourset which does not appear to return a set. Both the first and last elements are singular and therefore by convention not sets.
I would suggest logging the class of the return to confirm what, if anything, you're getting back.
Update:
(Forehead slap) The problem is actually the log statement itself. It should be:
NSLog(#"There are %d hourSets", [hourSets count]);
... because count returns an NSUInteger.