Get components of string to array, including the string as individual components - nsstring

componentsSeparatedByString: of NSString is nice, but this time I need it to include also the components. So a hypothetic
NSArray* array = [#",hello,world,kominami," componentsSeparatedByAndIncludingString:#","];
would give me an array with components
,
hello
,
world
,
kominami
,
Is there any such thing?

What action are you attempting to perform with this method?
There are a couple of ways to address that, but you could start with an array literal, but that is immutable:
NSArray *strings = #[ #[ #"A", #"B", #"C" ], #[ #"D", #"E", #"F" ], #[ #"G", #"H", #"I" ] ];
However I would look at a mutable array to perform this.
NSMutableArray *strings = [NSMutableArray array];
for(int i = 0; i < DESIRED_MAJOR_SIZE; i++)
{
[strings addObject: [NSMutableArray arrayWithObject:#""
count:DESIRED_MINOR_SIZE]];
}

Related

Declare array of strings

I was trying to declare an array of strings like so:
str ar1[2] = ['One','Two'];
Getting a syntax error. How can I initialize and assign an array like above?
['One', 'Two'] is a container in the axapta. axapta has no syntax for initialize an array. use:
str ar1[2];
ar1[1] = 'One';
ar1[2] = 'Two';
In AX, you'r trying to assign a container collection to an array collection. Which is incorrect, Therefore you can try to follow one of the approach listed below:
Using an array:
str number[2];
// Array starts at one in AX; hence number[0] will clear every value in the array
number[1] = 'One';
number[2] = 'Two';
The other way, would be to use a container:
container con;
con += 'One'; // Equivalent to 'con = conIns(con, conLen(con)+1, 'One');
con += 'Two'; // Equivalent to 'con = conIns(con, conLen(con)+1, 'Two');
or a shortcut would be to use:
container con = ['One', 'Two'];

Create nested map from key in groovy

I'm relatively new to groovy and am using it in the context of a gradle build. So please don't be harsh if there is an easy out-of-the-box solution for this.
Basically I'm trying to accomplish the reverse of Return Nested Key in Groovy. That is, I have some keys read from the System.properties map for example user.home and corresponding values like C:\User\dpr. Now I want to create a map that reflects this structure to use it in a groovy.text.SimpleTemplateEngine as bindings:
[user : [home : 'C:\Users\dpr']]
The keys may define an arbitrary deep hierarchy. For example java.vm.specification.vendor=Oracle Corporation should become:
[java : [vm : [spec : [vendor : 'Oracle Corporation']]]]
Additionally there are properties with the same parents such as user.name=dpr and user.country=US:
[
user: [
name: 'dpr',
country: 'US'
]
]
Edit: While ConfigSlurper is really nice, it is somewhat too defensive with creating the nested maps as it stops nesting at the minimum depth of a certain key.
I currently ended up using this
def bindings = [:]
System.properties.sort().each {
def map = bindings
def split = it.key.split("\\.")
for (int i = 0; i < split.length; i++) {
def part = split[i];
// There is already a property value with the same parent
if (!(map instanceof Map)) {
println "Skipping property ${it.key}"
break;
}
if (!map.containsKey(part)) {
map[part] = [:]
}
if (i == split.length - 1) {
map[part] = it.value
} else {
map = map[part]
}
}
map = it.value
}
With this solution the properties file.encoding.pkg, java.vendor.url and java.vendor.url.bug are discarded, which is not nice but something I can cope with.
However the above code is not very groovyish.
You can use a ConfigSlurper :
def conf = new ConfigSlurper().parse(System.properties)
println conf.java.specification.version

Unable to append items in value array of mutable dictionary

NSMutableDictionary *mutableDict = [NSMutableDictionary dictionaryWithDictionary: #{ #"Maruti":#[#"m1",#"m2"], #"Hyundai":#[#"h1",#"h2"] } ];
How can I add values in value array of each key so that my output would look like:
Maruti:[m1,m2,m3] Hyundai:[h1,h2,h3]
Both Maruti and hyundai dictionary are NSDictionary so you cannot add any new values into them , plus you cannot use any of them outside of the scope of this method, but if you still want to do something like this you can go with this.
NSMutableDictionary * tempDict = [[NSMutableDictionary alloc]init];
[tempDict setValue:#"5" forKey:#"number"];
[tempDict setValue:#"6" forKey:#"Hidden"];
NSMutableDictionary *tempDict2 = [[NSMutableDictionary alloc]init];
[tempDict setValue:#"5" forKey:#"number"];
[tempDict setValue:#"6" forKey:#"Hidden"];
NSMutableDictionary *mutableDict=[[NSMutableDictionary alloc] init];
[mutableDict setValue:tempDict forKey:#"Dict 1"];
[mutableDict setValue:tempDict2 forKey:#"Dict 2"];

Core Data: fetching items is slow with predicate

For my iPhone application I set up a data model for Core Data. It contains one entity Words and its attributes are language : String, length : Integer16 and word : String.
I prefilled my model's SQLite database with a word list (200k items) writing a separate iPhone application using the identical data model and coping the filled database to the main application.
Now using NSFetchedRequest I can query for managed objects as I like, but the results come in slow. I use the following method:
- (NSString *)getRandomWordLengthMin:(int)minLength max:(int)maxLength
{
NSString *word = #"";
MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Words"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSString *predicateString = #"length >= %d AND length <= %d";
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString,
minLength, maxLength];
[fetchRequest setPredicate:predicate];
NSError *error = nil;
int entityCount = [context countForFetchRequest:fetchRequest error:&error];
[fetchRequest setFetchLimit:1];
if(entityCount != 0)
{
[fetchRequest setFetchOffset:arc4random()%entityCount];
}
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if([fetchedObjects count] != 0)
{
Words * test = [fetchedObjects objectAtIndex:0];
word = [NSString stringWithFormat:#"%#", [test word]];
}
return word;
}
Using an SQLite editor I already set an index manually on column zLength, but this didn't bring any speedup. Where is the bottleneck?
EDIT:
I figured out that getting int entityCount = ... is slow. But even getting all objects and then selecting one random word is slow:
Words * test = [fetchedObjects objectAtIndex:arc4random()%[fetchedObjects count]];
You are effectively running two fetches here, one to get the fetch count and then one to fetch the actual object. That will slow things down.
Your predicate is "backwards." Compound predicates evaluate the first expression e.g. length >= %d and then evaluate the second e.g. length <= %d only against the results of the first. Therefore you should put the test that eliminates the most objects first. In this case, length <= %d probably eliminates more objects so it should come first in the predicate.
Since you don't actually need the entire Words managed object but just the word string, you can set the fetch return type to NSDictionaryResultType and then set the property to fetch to just the word attribute. That will speed things up considerably.
Part of your problem here is that Core Data is designed to managed a structured object graph and you are using a random/unstructured graph so you are cutting against the grain of Core Data's optimizations.
Do not use the SQLite editor to edit the SQLite backing store for a Core Data storage. The internals of the database is private and subject to change.
Instead go the the model editor in Xcode and simply put a checkmark on the "indexed" option for the entity attribute you want indexed.
Not sure but maybe this predicate is easier to optimize:
NSString *predicateString = #"length BETWEEN (%d, %d)";

Building an NSstring out of an NSMutableArray

My eyes hurt from hours of trying to figure this one - and i have looked for an answer for quite a while on-line (it will be embarrassing to tell how much...).
all i am trying to do is to enumerate using a for-in loop on anExpression which is a NSMutableArray that holds NSNumbers and NSStrings.
my NSLog print for the variable ans returns an empty string.
What am i doing wrong?
NSString *ans = #"";
for (id obj in anExpression)
{
if ([obj isKindOfClass:[NSString class]])
[ans stringByAppendingString:(NSString *)obj];
if ([obj isKindOfClass:[NSNumber class]])
[ans stringByAppendingString:(NSString *)[obj stringValue]];
NSLog(#"String so far: %# ", ans);
}
I think you mean
ans = [ans stringByAppendingString:(NSString *)obj];
not just
[ans stringByAppendingString:(NSString *)obj];
NSStrings are immutable -- you can't append to them. -stringByAppendingString: returns a new string (which you could then assign to ans).
Alternatively, you might use an NSMutableString and the -appendString: method.
Hey, sorry for the bad coding format, posting it again ...
NSString *ans = #"";
for (id obj in anExpression)
{
if ([obj isKindOfClass:[NSString class]])
[ans stringByAppendingString:(NSString *)obj];
if ([obj isKindOfClass:[NSNumber class]])
[ans stringByAppendingString:(NSString *)[obj stringValue]];
NSLog(#"String so far: %# ", ans);
}
[ans autorelease];
NSLog(#"final string is: %# ", ans);
return ans;
the method stringByAppendingString: returns a new string made by appending the given string to the receiver.
so you want ans = [ans stringByAppendingString:obj];

Resources