I've got a method that populated a prototype cell and two warnings are being throw and I'm not sure what to do.
First I am 'converting incompatible integer to pointer initializing BOOL...' With my declaration :
BOOL *isAVideo = [[feedItem objectForKey:#"isAVideo"]boolValue];
Second, when I use that variable in a comparison to check the object's value:
if (isAVideo == 1)
The warning states 'Comparison between pointer and integer'.
Here is the method for context:
- (void)setFeedItem:(PFObject *)feedItem
{
_feedItem = feedItem;
PFUser *user = [feedItem objectForKey:#"user"];
BOOL *isAVideo = [[feedItem objectForKey:#"isAVideo"]boolValue];
[_usernameButton setTitle:user.username
forState:UIControlStateNormal];
_captionView.text = [feedItem objectForKey:#"desc"];
_timestampLabel.text = [NSDate cks_stringForTimeSinceDate:feedItem.createdAt];
PFQuery *query = [PFQuery queryWithClassName:#"tfeed"];
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (object) {
// Object Found
NSLog(#"object found");
BOOL isVideo = [[object objectForKey:#"isAVideo"]boolValue];
NSLog(#"is a video: %d", isVideo);
if (isAVideo == 1) {
NSLog(#"object is a video");
}
BOOL is a primitive type, so remove the asterisk.
BOOL isAVideo = [[feedItem objectForKey:#"isAVideo"]boolValue];
To check this in an if statement use any the following:
if (isAVideo != NO) {
//true
}
if (isAVideo == YES) {
//true
}
if (isAVideo) {
//true
}
if (isAVideo == NO) {
//false
}
if (!isAVideo) {
//false
}
Related
I have a predicate for query in core data base but i don't know what is the correct way to validate its params?
- (void) queryToDatabaseWithStoreId:(NSInteger) storeId {
[NSPredicate predicateWithFormat:#"store.storeId = %d", storeId];
}
My question is how can i validate storeId param or what i need to use for that vulnerability to dissapear?
And if i have a list:
- (void) queryToDataBaseWithListStore:(NSArray<Store *> *) storeList {
[NSPredicate predicateWithFormat:#"store.storeId IN %#", [storeList valueForObject:#"storeId"]];
}
https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Articles/ValidatingInput.html#//apple_ref/doc/uid/TP40007246-SW3
I need avoid that:
The following commonly-used functions and methods are subject to format-string attacks:
Standard C
printf and other functions listed on the printf(3) manual page
sscanf and other functions listed on the scanf(3) manual page
syslog and vsyslog
Carbon
AEBuildDesc and vAEBuildDesc
AEBuildParameters and vAEBuildParameters
AEBuildAppleEvent and vAEBuildAppleEvent
Core Foundation
CFStringCreateWithFormat
CFStringCreateWithFormatAndArguments
CFStringAppendFormat
CFStringAppendFormatAndArguments
Cocoa
stringWithFormat:, initWithFormat:, and other NSString methods that take formatted strings as arguments
appendFormat: in the NSMutableString class
alertWithMessageText:defaultButton:alternateButton:otherButton:informativeTextWithFormat: in NSAlert
predicateWithFormat:, predicateWithFormat:arguments:, and predicateWithFormat:argumentArray: in NSPredicate
raise:format: and raise:format:arguments: in NSException
NSRunAlertPanel and other AppKit functions that create or return panels or sheets
What is the best way to avoid this attack?
I have programmed this class but i don't know if it is enough.
#implementation StringUtils
+ (BOOL) isEmpty:(id) text {
if ([text isKindOfClass:[NSNull class]]) {
return YES;
} else {
if (text) {
if ([text isKindOfClass:[NSString class]]) {
NSString *textStr = [NSString stringWithFormat:#"%#", text];
return [textStr isEqualToString:#""];
}
return YES;
} else {
return YES;
}
}
}
+ (NSString *) validateField:(id) text {
NSInteger numErrors = 0;
NSString *pattern = #"[^A-Za-z0-9-]+";
NSError *error = nil;
NSString *textValidated = #"";
if ([text isKindOfClass:[NSNumber class]]) {
textValidated = [text stringValue];
} else if ([text isKindOfClass:[NSString class]]) {
textValidated = text;
} else {
#try {
textValidated = [text stringValue];
} #catch (NSException *exception) {
numErrors=+1;
}
}
//Only numbers && chars && -
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSRange textRange = NSMakeRange(0, textValidated.length);
NSRange matchRange = [regex rangeOfFirstMatchInString:textValidated options:NSMatchingReportProgress range:textRange];
if (matchRange.location != NSNotFound) {
numErrors+=1;
}
//Not empty string
if ([StringUtils isEmpty:textValidated]) {
numErrors+=1;
}
if (numErrors == 0) {
return textValidated;
}
return #"";
}
+ (NSArray *) validateArrayFields:(NSArray *) list {
NSInteger *numErrors = 0;
for (id obj in list) {
if ([StringUtils isEmpty:[StringUtils validateField:obj]]) {
numErrors+=1;
}
}
if (numErrors == 0) {
return list;
}
return [[NSArray alloc] init];
}
#end
For use normal:
[NSPredicate predicateWithFormat:#"store.storeId = %#", [StringUtils validateField:storeId]];
For use with array:
[NSPredicate predicateWithFormat:#"store.storeId IN %#", [StringUtils validateArrayFields:storeId]];
What round brackets do to a typedef in the line optionAction = attempter(option); ?
Is that casting?
The full code:
- (id<ISFModalMessageView>)modalMessageWithError:(NSError *)error recoveryAttempter:(SFErrorRecoveryAttempter)attempter
{
if ([self shouldNotifyUserForError:error] && [self typeForError:error] == SFErrorTypeAlert)
{
NSString *title = [self titleForError:error];
NSString *message = [self messageForError:error];
SFAlertMessageView *alert = [[SFAlertMessageView alloc]initWithTitle:title message:message image:nilcancelButton:#"Cancel"];
SFErrorRecoveryOption option = [self recoveryOptionForError:error];
if (option != SFErrorRecoveryOptionUndefiend)
{
NSString *optionTitle = [self titleForRecoveryOptionOfError:error];
SFModalMessageAction optionAction = nil;
if (attempter) {
optionAction = attempter(option); // This Part
}
if (optionTitle.notEmpty && optionAction) {
[alert addActionButtonWithTitle:optionTitle action:optionAction];
}
}
return alert;
}
return nil;
}
SFErrorRecoveryOption:
typedef NS_ENUM(NSUInteger, SFErrorRecoveryOption) {
SFErrorRecoveryOptionUndefiend = 0,
SFErrorRecoveryOptionTryAgain,
SFErrorRecoveryOptionReport,
SFErrorRecoveryOptionSignIn,
SFErrorRecoveryOptionSignUp,
SFErrorRecoveryOptionReset,
SFErrorRecoveryOptionSignInFacebook,
};
SFModalMessageAction:
typedef void (^ SFModalMessageAction)() ;
SFErrorRecoveryAttempter:
typedef SFModalMessageAction (^ SFErrorRecoveryAttempter)(SFErrorRecoveryOption option);
Most likely SFErrorRecoveryAttempter is typedefed to some block type and line in question
attempter(option);
is just calling a block passed to your method as parameter. Note that calling a nil block will result in exception, so if (attempter) check is added
I have the following function written in Objective C using blocks and I am trying to convert it to swift, but I am banging my head against the wall and can't get it sorted.
Here is the code in Objective C
typedef void (^ResponseBlock) (BOOL succeeded, NSArray* data);
- (void)findAllMediaFromDate:(NSDate*)createdAtDate block:(ResponseBlock)block
{
NSMutableArray *results = [NSMutableArray array];
PFQuery *query = [PFQuery queryWithClassName:PARSE_MODEL_ACTIVITIES];
[query orderByDescending:#"createdAt"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
for (ActivityObject *object in objects) {
if ([object.media.type isEqualToString: #"video"] || [object.media.type isEqualToString: #"photo"]) {
[results addObject:object];
}
}
block(YES, results);
}
else {
}
}];
}
Now here is what I have in SWIFT. It's a different function body, but the syntax I am trying is the same...
func userQuery (){ //This needs to return an array as ABOVE
var results = [UserModel]()
println("NM: userQuery")
var query = UserModel.query()
query.whereKey("objectId", equalTo:"7N0IWUffOZ")
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!, error:NSError!) -> Void in
if (objects != nil) {
NSLog("yea")
for object in objects{
results.append(object as UserModel)
//Need to return the array to the userQuery function
}
} else {
NSLog("%#", error)
}
}
}
```
You can add the closure parameter like so:
func userQuery(completionHandler: (succeeded: Bool, array: [UserModel]?) -> ()) {
// do your other stuff here
if objects != nil {
// build results
completionHandler(succeeded: true, array: results)
} else {
// return failure
completionHandler(succeeded: false, array: nil)
}
}
Clearly, change your array parameter to be whatever you want (rename it, change the type, whatever), but the basic idea is to have an optional array return type.
And you can call it using the trailing closure syntax, like so:
userQuery() {
success, results in
if success {
// use results here
} else {
// handle error here
}
}
By the way, if you like the Objective-C typedef pattern, the equivalent in Swift is typealias:
typealias ResponseClosure = (succeeded: Bool, array: [UserModel]?) -> ()
func userQuery(completionHandler: ResponseClosure) {
// the same as above
}
<\RESOLVED>, Please see the first reply
My mac(10.9) has joined into a AD domain. In my program, I tried to recognize whether the current login user is local account or AD user. I can successfully distinguish them by using the following code.
+ (bool)isLocalUser:(NSString*)user
{
NSError *dirSearchError = nil;
ODRecord *foundUser = findUser(user, &dirSearchError);
if(foundUser !=nil)
{
return YES;
}else
{
return NO;
}
}
ODRecord *findUser(NSString *user, NSError **error)
{
NSLog(#"[MacLogonUI] findUser");
ODNode *searchNode = [ODNode nodeWithSession: [ODSession defaultSession]
type: kODNodeTypeLocalNodes
error: error];
if (searchNode == nil) {
return nil;
}
NSDictionary *nodeInfo = [searchNode nodeDetailsForKeys:nil error:error];
/* query this node for the user record we're interested in.
* We only need one result, which is why maximumResults is set to 1.
*/
ODQuery *userSearch = [ODQuery queryWithNode: searchNode
forRecordTypes: kODRecordTypeUsers
attribute: kODAttributeTypeRecordName
matchType: kODMatchEqualTo
queryValues: user
returnAttributes: kODAttributeTypeStandardOnly
maximumResults: 1
error: error];
if (userSearch == nil) {
return nil;
}
/* For this example we'll use a synchronous search. This could take a while
* so asynchronous searching is preferable.
*/
NSArray *foundRecords = [userSearch resultsAllowingPartial: NO error: error];
if (foundRecords == nil || [foundRecords count] == 0) {
return nil;
}
ODRecord *userRecord = [foundRecords objectAtIndex: 0];
return [[userRecord retain] autorelease];
}
While when the AD user create a mobile card, it is viewed as a managed user(from the System preference -> Users & Groups). The code also recognize this kind of AD user as local. How to deal with this kind of situation?
Do you guys have any idea of this problem?
I have solved this problem by myself. Hope the following code helps:
#import "DasUser.h"
#import <OpenDirectory/OpenDirectory.h>
#import <Collaboration/Collaboration.h>
#implementation DasUser
+ (bool)isLocalUser:(NSString*)user
{
NSError *dirSearchError = nil;
ODRecord *foundUser = findUser(user, &dirSearchError);
if(foundUser !=nil)
{
return YES;
}else
{
return NO;
}
}
ODRecord *findUser(NSString *user, NSError **error)
{
NSLog(#"[MacLogonUI] findUser");
CSIdentityAuthorityRef defaultAuthority = CSGetManagedIdentityAuthority();
CSIdentityClass identityClass = kCSIdentityClassUser;
CSIdentityQueryRef query = CSIdentityQueryCreate(NULL, identityClass, defaultAuthority);
CFErrorRef err = NULL;
CSIdentityQueryExecute(query, 0, &err);
CFArrayRef results = CSIdentityQueryCopyResults(query);
int numResults = CFArrayGetCount(results);
NSMutableArray * managedUsers = [NSMutableArray array];
for (int i = 0; i < numResults; ++i) {
CSIdentityRef identity = (CSIdentityRef)CFArrayGetValueAtIndex(results, i);
CBIdentity * identityObject = [CBIdentity identityWithCSIdentity:identity];
NSString* posixName = [identityObject posixName];
[managedUsers addObject:posixName];
}
CFRelease(results);
CFRelease(query);
ODNode *searchNode = [ODNode nodeWithSession: [ODSession defaultSession]
type: kODNodeTypeLocalNodes
error: error];
if (searchNode == nil) {
return nil;
}
/* query this node for the user record we're interested in.
* We only need one result, which is why maximumResults is set to 1.
*/
ODQuery *userSearch = [ODQuery queryWithNode: searchNode
forRecordTypes: kODRecordTypeUsers
attribute: kODAttributeTypeRecordName
matchType: kODMatchEqualTo
queryValues: user
returnAttributes: kODAttributeTypeStandardOnly
maximumResults: 1
error: error];
if (userSearch == nil) {
return nil;
}
/* For this example we'll use a synchronous search. This could take a while
* so asynchronous searching is preferable.
*/
NSArray *foundRecords = [userSearch resultsAllowingPartial: NO error: error];
if([foundRecords count]>0)
{
NSString *nameStr = [foundRecords[0] recordName];
NSLog(#"[MacLogonUI] findUser nameStr %#", nameStr);
int j;
for( j = 0; j<[managedUsers count]; j++)
{
if([nameStr isEqualToString:managedUsers[j]])
{
break;
}
}
if(j<[managedUsers count])
{
foundRecords = nil;
}
}
if (foundRecords == nil || [foundRecords count] == 0) {
return nil;
}
ODRecord *userRecord = [foundRecords objectAtIndex: 0];
return [[userRecord retain] autorelease];
}
#end
While when network of the mac is disconnected. The managed user can not be listed. Is there anybody has any idea of this?
Hey i got a Question regarding inserting data into an sqlite database. I want to create general class for inserting data into a sqlite database. so i wrote a method like this:
-(void)saveData:(char)sqlstmnt andValues:(NSArray *)Values {
char *sql= &sqlstmnt;
sqlite3_prepare_v2(database, sql, -1, &statement, NULL);
}
Now my problem is the given Array "Values" could be send by different classes and the content of that array is diffrent every time this method is called. it contains int, bool, float, text. so is there a way or a method that could "scan" with type a part of an array got?
something like:
if ([Values objectAtIndex:i isINT]) {
sqlite3_bind_int(statement, i, [Values objectAtIndex:i]);
}
if ([Values objectAtIndex:i isFLOAT]) {
sqlite3_bind_float(statement, i, [Values objectAtIndex:i]);
}
if ([Values objectAtIndex:i isAnBOOL]) {
sqlite3_bind_bool(statement, i, [Values objectAtIndex:i]);
}
it would be great if anybody could help me with that.
because i need the type of it
Use isKindOfClass: and objCType
id object = ...
if ([object isKindOfClass:[NSString class]]) {
// object is a string
}
else if ([object isKindOfClass:[NSNumber class]]) {
if (strcmp([object objCType], #encode(BOOL)) == 0) {
// bool
}
else if (strcmp([object objCType], #encode(int)) == 0) {
// int
}
else if (strcmp([object objCType], #encode(float)) == 0) {
// float
}
else if (strcmp([object objCType], #encode(double)) == 0) {
// double
}
// and so on
}