I have NSMutableData array of bytes. I need to find item and then delete it.
my code:
NSArray *array = [[tunerButtonHostInfo objectForKey:#"local"] objectForKey:#"snPacket"];
NSMutableData *asciiData = [[NSMutableData alloc] init];
[asciiData appendData [#"\x00\x00\x02\x00\x00\x0e"dataUsingEncoding:NSASCIIStringEncoding]];
if(array != nil && ![array isKindOfClass:[NSNull class]] && [array isKindOfClass:[NSArray class]]) {
for(NSNumber *asciiCode in array) {
int asc = [asciiCode intValue];
if(asc == 0) {
NSString *string = #"\x00"; dataUsingEncoding:NSASCIIStringEncoding]];
}
else {
NSString *converted = [NSString stringWithFormat:#"%c", asc];
[asciiData appendData:[converted dataUsingEncoding:NSUTF8StringEncoding]];
}
}
NSLog(#"stringAsciiData"); //print asciiData
NSLog(#"%#", asciiData);
output of asciiData is:
00000200 000e6808 08680064 6c0b0367 6308c2b0 16
I need to find "c2" in the array and then remove it and shift remaining data in array to the left
Here is the modification to code to c2 . You can use append bytes method instead of converting to string and printing it back:
{
NSArray *array = #[#68,#0x08,#0x08,#68,#00,#64,#0x6c,#0x0b,#03,#67,#63,#0x08,#0xc2,#0xb0,#16];
NSMutableData *asciiData = [[NSMutableData alloc] init];
[asciiData appendData:[#"\x00\x00\x02\x00\x00\x0e"dataUsingEncoding:NSASCIIStringEncoding]];
if(array != nil && ![array isKindOfClass:[NSNull class]] && [array isKindOfClass:[NSArray class]]) {
for(NSNumber *asciiCode in array) {
Byte asc = [asciiCode intValue];
if(asc == 0) {
NSString *string = #"\x00";
[asciiData appendData:[string dataUsingEncoding:NSASCIIStringEncoding]];
}else if(asc != 0xc2) {
[asciiData appendBytes:&asc length:1];
}
}
NSLog(#"stringAsciiData"); //print asciiData
NSLog(#"%#", asciiData);
}
}
Related
I want to concatenate some strings from variables if the variables are not nil. If they are nil, I don't want to include them. The following code works but is clunky and grows proportionately more complex with additional variables. Can anyone recommend a more elegant way to do this?
NSString *city = self.address.city== nil ? #"" : self.address.city;
NSString *state = self.address.state== nil ? #"" : self.address.state;
NSString *zip = self.address.zip== nil ? #"" : self.address.zip;
NSString *bestCity;
if (city.length>0&&state.length>0&&zip.length>0) {
bestCity = [NSString stringWithFormat: #"%# %# %#", city, state,zip];
}
else if (city.length>0&&state.length>0) {
bestName = [NSString stringWithFormat: #"%# %#", city,state];
}
else if (city.length>0&&zip.length>0) {
bestCity = [NSString stringWithFormat: #"%# %#", city,zip];
}
else if (city.length>0&&zip.length>0) {
bestCity = [NSString stringWithFormat: #"%# %#", city,zip];
}
else if (city.length>0) {
bestCity = [NSString stringWithFormat: #"%#", city];
}
else if (state.length>0) {
bestCity = [NSString stringWithFormat: #"%#", state];
}
else if (zip.length>0) {
bestCity = [NSString stringWithFormat: #"%#", zip];
}
else {
bestCity = #"";
}
I usually do something like:
NSMutableArray *bestCityArr = [#[] mutableCopy]; // [[NSMutableArray alloc] init];
if (city.length > 0)
[bestCityArr addObject:city];
if (state.length > 0)
[bestCityArr addObject:state];
if (zip.length > 0)
[bestCityArr addObject:zip];
NSString *bestCity = [bestCityArr componentsJoinedByString:#" "];
NSMutableArray *items = [[NSMutableArray alloc] init];
if (self.address.city)
[items appendObject:self.address.city];
if (self.address.state)
[items appendObject:self.address.state];
if (self.address.zip)
[items appendObject:self.address.zip];
NSString *bestCity = [items componentsJoinedByString:#" "];
This code may help you!
- (NSString *)concatenateString
{
NSMutableString *bestCity = [NSMutableString string];
NSString *city = self.address.city ?: #"";
[bestCity appendString:city];
NSString *state = self.address.state ?: #"";
if (state.length > 0) {
[bestCity appendString:#" "];
}
[bestCity appendString:state]];
NSString *zip = self.address.zip ?: #"";
if (zip.length > 0) {
[bestCity appendString:#" "];
}
[bestCity appendString:zip];
return bestCity.length > 0 ? bestCity : #"";
}
i have test array with objects structure - Group with (NSMutableArray)items, and i save group in YapDatabase
-(void)parseAndSaveJson:(id) json withCompleteBlock:(void(^)())completeBlock{
NSMutableArray *groupsArray = (NSMutableArray *)json;
if (groupsArray != nil) {
YapDatabaseConnection *connectnion = [[DatabaseManager sharedYapDatabase] newConnection];
[connectnion asyncReadWriteWithBlock:^(YapDatabaseReadWriteTransaction *transaction) {
for (int groupIndex = 0; groupIndex < [groupsArray count]; groupIndex ++) {
LocalGroupsExercise *localGroup = [[LocalGroupsExercise alloc] init];
localGroup.name = groupsArray[groupIndex][LOCAL_GROUPS_NAME];
localGroup.tagColor = groupsArray[groupIndex][LOCAL_GROUPS_TAG_COLOR];
localGroup.idGroup = [groupsArray[groupIndex][LOCAL_GROUPS_ID_GROUP] intValue];
if (groupsArray[groupIndex][LOCAL_GROUPS_EXERCISES] != nil) {
NSMutableArray *exerciseArray = (NSMutableArray *)groupsArray[groupIndex][LOCAL_GROUPS_EXERCISES];
for (int exerciseIndex = 0; exerciseIndex < [exerciseArray count]; exerciseIndex ++) {
LocalExercise *localExercise = [[LocalExercise alloc] init];
localExercise.name = exerciseArray[exerciseIndex][EXERCISE_NAME];
localExercise.exerciseId = [exerciseArray[exerciseIndex][LOCAL_EXERCISE_ID_EXERCISE] intValue];
localExercise.groupId = localGroup.idGroup;
localExercise.type = [exerciseArray[exerciseIndex][EXERCISE_TYPE] intValue];
localExercise.minWeight = [exerciseArray[exerciseIndex][EXERCISE_MIN_WEIGHT] floatValue];
localExercise.maxWeight = [exerciseArray[exerciseIndex][EXERCISE_MAX_WEIGHT] floatValue];
localExercise.minReps = [exerciseArray[exerciseIndex][EXERCISE_MIN_REPS] intValue];
localExercise.maxReps = [exerciseArray[exerciseIndex][EXERCISE_MAX_REPS] intValue];
localExercise.minTimer = [exerciseArray[exerciseIndex][EXERCISE_MIN_TIMER] intValue];
localExercise.maxTimer = [exerciseArray[exerciseIndex][EXERCISE_MAX_TIMER] intValue];
localExercise.timeRelax = [exerciseArray[exerciseIndex][EXERCISE_RELAX_TIME] intValue];
[localGroup.exercises addObject:localExercise];
}
}
[transaction setObject:localGroup forKey:[NSString stringWithFormat:#"%d", localGroup.idGroup] inCollection:LOCAL_GROUPS_CLASS_NAME];
}
YapDatabaseConnection *connectnion = [[DatabaseManager sharedYapDatabase] newConnection];
[connectnion readWithBlock:^(YapDatabaseReadTransaction *transaction) {
LocalGroupsExercise *group = [transaction objectForKey:#"2" inCollection:LOCAL_GROUPS_CLASS_NAME];
NSLog(#"%#", group.name);
NSLog(#"%#", group.tagColor);
NSLog(#"%#", group.exercises);
}];
} completionBlock:^{
completeBlock();
}];
}
}
+ (YapDatabaseView *)setupDatabaseViewForShowGroupsGyms{
YapDatabaseViewGrouping *grouping = [YapDatabaseViewGrouping withObjectBlock:^NSString *(YapDatabaseReadTransaction *transaction, NSString *collection, NSString *key, id object) {
if ([object isKindOfClass:[LocalGroupsExercise class]]) {
LocalGroupsExercise *groupExercise = (LocalGroupsExercise *)object;
return [NSString stringWithFormat:#"%#", groupExercise.name];
}
return nil;
}];
YapDatabaseViewSorting *sorting = [YapDatabaseViewSorting withObjectBlock:^NSComparisonResult(YapDatabaseReadTransaction *transaction, NSString *group, NSString *collection1, NSString *key1, LocalGroupsExercise *obj1, NSString *collection2, NSString *key2, LocalGroupsExercise *obj2) {
return [obj1.name compare:obj2.name options:NSNumericSearch range:NSMakeRange(0, obj1.name.length)];
}];
YapDatabaseView *databaseView = [[YapDatabaseView alloc] initWithGrouping:grouping sorting:sorting versionTag:#"0"];
return databaseView;
}
[[DatabaseManager sharedYapDatabase] registerExtension:self.databaseGroupView withName:LOCAL_GROUPS_CLASS_NAME];
[_connection beginLongLivedReadTransaction];
self.mappingsGroup = [[YapDatabaseViewMappings alloc] initWithGroupFilterBlock:^BOOL(NSString *group, YapDatabaseReadTransaction *transaction) {
return true;
} sortBlock:^NSComparisonResult(NSString *group1, NSString *group2, YapDatabaseReadTransaction *transaction) {
return [group1 compare:group2];
} view:LOCAL_GROUPS_CLASS_NAME];
[_connection readWithBlock:^(YapDatabaseReadTransaction *transaction) {
[self.mappingsGroup updateWithTransaction:transaction];
}];
The problem is that the group be NSMutabblArray and I want to see the objects in the table of the array, but [self.mappingsGroup numberOfItemsInSection:section] return only one items in group
You need to configure YapDatabase to use Mantle. By default, it will use NSCoding. (Which is why you're seeing an error about "encodeWithCoder:", as that method is part of NSCoding.)
Take a look at YapDatabase's wiki article entitled "Storing Objects", which talks about how it uses the serializer/deserializer blocks: https://github.com/yaptv/YapDatabase/wiki/Storing-Objects
Basically, when you alloc/init your YapDatabase instance, you'll want to pass a serializer & deserializer block that uses Mantle to perform the serialization/deserialization.
Also, see the various init methods that are available for YapDatabase: https://github.com/yaptv/YapDatabase/blob/master/YapDatabase/YapDatabase.h
This works fine if the textField is containing any text. But if the textField is empty, no objects are added.
How to tell this piece of code that if the textField is empty, all objects should be added to resultObjectsArray?
resultObjectsArray = [NSMutableArray array];
for(NSDictionary *object in allObjectsArray)
{
NSString *nameString = [NSString stringWithFormat:#"%#", [textField text]];
NSString *wineName = [wine objectForKey:#"Name"];
NSRange range = [wineName rangeOfString:nameString options:NSCaseInsensitiveSearch];
if ((range.location != NSNotFound))
[resultObjectsArray addObject:object];
}
resultObjectsArray = [NSMutableArray array];
NSString *nameString = [textField text];
for(NSDictionary *object in allObjectsArray)
{
if ([nameString length] > 0)
{
NSString *wineName = [wine objectForKey:#"Name"];
NSRange range = [wineName rangeOfString:nameString options:NSCaseInsensitiveSearch];
if ((range.location != NSNotFound))
[resultObjectsArray addObject:object];
}
else
{
[resultObjectsArray addObject:object];
}
}
Note that you don't need:
NSString *nameString = [NSString stringWithFormat:#"%#", [textField text]];
as
NSString *nameString = [textField text];
is sufficient. Also it won't change inside the for loop so can be initialised outside of it.
That's how the code ended up looking like using the answer from #trojanfoe. (I've excluded my other search criterias).
-(IBAction)searchButtonPressed:(id)sender{
BOOL textFieldIsEdited = NO;
if ([[textField text] length] > 0)
{
textFieldIsEdited = YES;
}
resultObjectsArray = [NSMutableArray array];
for(NSDictionary *wine in allObjectsArray)
{
BOOL nameMatch = YES;
if (textFieldIsEdited) {
NSString *wineName = [wine objectForKey:#"Name"];
NSString *nameString = [textField text];
NSRange range = [wineName rangeOfString:nameString options:NSCaseInsensitiveSearch];
if (range.location == NSNotFound) {
nameMatch = NO;
}
}
if ((nameMatch != NO))
[resultObjectsArray addObject:wine];
}
I am getting rows from a SQLite DB and trying to insert them into a dictionary. Except I keep getting errors! I get the error "Implicit conversion of an Objective-C pointer to 'const id *' is disallowed with ARC" Which I know means that I cant use a pointer when I am adding objects to my dictionary. So how do I go about fixing it so I can add those arrays to a dictionary?
NSArray *keyArray = [[NSMutableArray alloc] init ];
NSArray *valueArray = [[NSMutableArray alloc ] init ];
NSDictionary* dic;
NSInteger dataCount = sqlite3_data_count(statement);
while (sqlite3_step(statement) == SQLITE_ROW) {
#try {
for (int i = 0; i < dataCount; i ++)
{
NSString* key = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, i)];
NSString *value = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, i)];
if ([value length] == 0)
{
value = #"";
}
keyArray = [keyArray arrayByAddingObject:key];
valueArray = [valueArray arrayByAddingObject:value];
}
}
#catch (NSException *ex)
{
NSLog(#"%#,%#", [ex name], [ex reason]);
}
dic= [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray count:[keyArray count]];
The dictionaryWithObjects:forKeys:count: takes C-style arrays, not NSArray objects. The dictionaryWithObjects:forKeys: may do the trick, but you may be better off constructing a mutable dictionary as you go, bypassing NSArrays entirely.
NSDictionary* dic;
NSMutableDictionary *tmp = [NSMutableDictionary dictionary];
for (int i = 0; i < dataCount; i ++)
{
NSString* key = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, i)];
NSString *value = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, i)];
[tmp setObject:value forKey:key];
}
dict = tmp;
[dicBodyPost setValue:arrContactAddress forKey:#"contactAddress"];
I'm developing an iPhone app. I've got a function that reads data from a sqlite database and puts the results into an array. Everything works fine. Here is part of the function that fills the array:
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSString *aVar1 = [NSString stringWithUTF8String(char*)sqlite3_column_text(compiledStatement, 0)];
NSString *aVar2 = [NSString stringWithUTF8String(char*)sqlite3_column_text(compiledStatement, 1)];
NSArray *anArray = [NSArray arrayWithObjects:aVar1,aVar2,nil];
[returnArray addObject:anArray]
[anArray release];
}
//return the array
I want to make this function more generic so that it takes a sql statement string as a parameter, and returns a mutablearray of arrays, no matter how many columns are in the result set.
Is there a way to do this? The solution doesn't have to include arrays -- could be any collection object. I'm just looking for a way to make the function re-usable for other queries to the same database.
Couldn't you just do something like:
int numCols = sqlite3_column_count(compiledStatement);
NSMutableArray *result = [NSMutableArray array];
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < numCols; i++) {
[array addObject:
[NSString stringWithUTF8String:
(char *)sqlite3_column_text(compiledStatement, i)]];
}
[result addObject:array];
}
+(NSArray *)executeQueryAndReturnArray:(NSString *)query {
sqlite3_stmt *statement = nil;
const char *sql = [query UTF8String];
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) != SQLITE_OK) {
NSLog(#"[SQLITE] Error when preparing query!");
} else {
NSMutableArray *result = [NSMutableArray array];
while (sqlite3_step(statement) == SQLITE_ROW) {
NSMutableArray *row = [NSMutableArray array];
for (int i = 0; i < sqlite3_column_count(statement); i++) {
int colType = sqlite3_column_type(statement, i);
id value;
if (colType == SQLITE_TEXT) {`enter code here`
const unsigned char *col = sqlite3_column_text(statement, i);
value = [NSString stringWithFormat:#"%s", col];
} else if (colType == SQLITE_INTEGER) {
int col = sqlite3_column_int(statement, i);
value = [NSNumber numberWithInt:col];
} else if (colType == SQLITE_FLOAT) {
double col = sqlite3_column_double(statement, i);
value = [NSNumber numberWithDouble:col];
} else if (colType == SQLITE_NULL) {
value = [NSNull null];
} else {
NSLog(#"[SQLITE] UNKNOWN DATATYPE");
}
[row addObject:value];
}
[result addObject:row];
}
return result;
}
return nil;
}