TWTRSession issue with TwitterKit 3.3.0 - ios

let sessions = TWTRTwitter.sharedInstance().sessionStore.existingUserSessions()
supposedly returns an array of TWTRSessions.
However the type of the elements is untyped (Any), and casting to TWTRSession using if let authsession = any as? TWTRSession fails. Also, force casting crashes obviously.
let authsession = any as! TWTRSession // crashes
Crash error:
Could not cast value of type 'TWTRSession' (0x103fbe370) to 'TWTRSession' (0x103cf5cc8).
That's a very interesting error, don't you think? TWTRSession matches, but sure, the hex values do not.
Oh, this worked up until before 3.3.0. No release notes or migration notes from the folks at Twitter. Things just silently stopped working.
Related: TWTRTwitter sessionStore now returns TWTRAuthSession: so how does one access the userName property now?

I ended up creating a C function to recreate the array and call it from my Swift file:
NSArray<TWTRSession *> *existingUserSessions(TWTRSessionStore *store) {
NSArray<TWTRSession *> *existingSessions = store.existingUserSessions;
NSUInteger count = existingSessions.count;
NSMutableArray<TWTRSession *> *sessions = [NSMutableArray arrayWithCapacity:count];
for (TWTRSession *session in existingSessions) {
[sessions addObject:session];
}
return [sessions copy];
}

Related

What is the Use of "NSNumber numberWithInt" in Xcode

i'm retrieving data from server - where the NS Number used contains BOOL value in database format. but when i try to use TRUE or FALSE , it doest allow to do.
- i'm a Beginner of Xcode.
for (unsigned int i =0; i<studentDashBoardDetails.count; i++) {
// Early CheckOut Days
if ([[[ studentDashBoardDetails objectAtIndex:i]objectForKey:#"dayType"]isEqualToString: #"Working"]&&[[[studentDashBoardDetails objectAtIndex:i]objectForKey:#"isAttended"]isEqualToNumber:[NSNumber numberWithInt:1]]&&[[[studentDashBoardDetails objectAtIndex:i]objectForKey:#"timeSpent"]isLessThan:#"08.00.00"])
{
NSLog(#" Early Check out on %#",[[studentDashBoardDetails objectAtIndex:i]objectForKey:#"attendanceDate"]);
NSNumber numberWithInt returns the signed integer for the current value, to access bool values you can use NSNumber numberWithBool method, it creates an object and returns NSNumber which can be treated as a bool.
I hope it will help you in achieving proper way on how to solve your problem
While saving save as NSNumber like this
NSNumber *isAttended = [[studentDashBoardDetails objectAtIndex:i]objectForKey:#"isAttended"];
and while reading it do your condition like this
if (isAttended.boolValue){
//true
}else{
//false
}
in your case you have to do like this
if ([[[ studentDashBoardDetails objectAtIndex:i]objectForKey:#"dayType"]isEqualToString: #"Working"] && isAttended.boolValue &&[[[studentDashBoardDetails objectAtIndex:i]objectForKey:#"timeSpent"]isLessThan:#"08.00.00"])
{
NSLog(#" Early Check out on %#",[[studentDashBoardDetails objectAtIndex:i]objectForKey:#"attendanceDate"]);
}

different object type returned than the one in function body swift objc

I have been searching day and night for this. I seem to be the first one getting such an annoying error. I have a swift app and have imported an objective C framework(XlsxReaderWriter) by cocoa pods. Everything is working except Nothing is returned as the type specified in the functions in the objective C framework. Everything is returned as Any.
Forexample;
inputFile: BRAWorksheet = file.workbook.worksheets![0] //this gives me a compile error saying "Can not assign value of type Any to BRAWorksheet"
and here is the property declaration in objective C
- (NSArray *)worksheets {
NSMutableArray *worksheets = #[].mutableCopy;
for (BRASheet *sheet in _sheets) {
BRAWorksheet *worksheet = [self.relationships relationshipWithId:sheet.identifier];
worksheet.styles = _styles;
worksheet.sharedStrings = _sharedStrings;
worksheet.calcChain = _calcChain;
[worksheets addObject:worksheet];
}
return worksheets.count ? worksheets : nil;
}
even in the documentation for the library, that is how they do it;
var firstWorksheet: BRAWorksheet = spreadsheet.workbook.worksheets[0]
So can anyone tell me what this strange error is please?? I am getting desperate.
PS: I do not want to cast for some reasons
Instead of NSArray *, set the return type of the method to NSArray<BRAWorksheet *> *.

Return unique/distinct values with Realm query

I have a Message/RLMObject model that has a NSString *jabberID property/row and I want to retrieve every unique value inside that row.
In other word, I want to retrieve non-repeated jabberID values from my Message model. Can anyone help out figuring this?
The way I use to do with coredata was using returnsDistinctResults setting on the NSFetchRequest.
Functional programming approach since Swift has it, and Realm lazy loads; Not as easy/available a solution in Objective-C but for Swift at least:
Swift
let distinctTypes = reduce(Realm().objects(User), []) { $0 + (!contains($0, $1.type) ? [$1.type] : [] ) }
UPDATED:
Swift reduce is kind of a performance intensive, allocating a bunch of intermediate array's, instead the following should be much better performance wise, but must be explicitly cast
let distinctTypes = Array(Set(Realm().objects(User).valueForKey("type") as! [String]))
I found out Realm doesn't fully support distinct queries yet. The good news is I also found a workaround for it, on this github issue.
Objective-c
RLMResults *messages = [Message allObjects];
NSMutableArray *uniqueIDs = [[NSMutableArray alloc] init];
NSMutableArray *uniqueMessages = [[NSMutableArray alloc] init];
for (Message *msg in messages) {
NSString *jabberID = msg.jabberID;
Message *uniqueMSG = (Message *)msg;
if (![uniqueIDs containsObject:jabberID]) {
[uniqueMessages addObject:uniqueMSG];
[uniqueIDs addObject:jabberID];
}
}
Swift 3.0
let realm = try! Realm()
let distinctIDs = Set(realm.objects(Message.self).value(forKey: "jabberID") as! [String])
var distinctMessages = [Message]()
for jabberID in distinctIDs {
if let message = realm.objects(Message.self).filter("jabberID = '\(jabberID)'").first {
distinctMessages.append(message)
}
}

can I switch NSString

I want to switch NSString in XmlParser because if there are 15 or more web-service then every time the loop check for correct element in IF..ELSE.That I don't want to make processor busy..
I have searched a lot and found using enum I can switch NSString but no luck ..
I have tried each possibilities,but some where i am making mistake.
Please help to solve this big problem for me.
Here I have declare my enum:
Here in "elementName" I am getting Exact value as declared in enum:
But instead of 1, I am getting wrong value Like 202896536:
You cant do it by creating enum. You must need to compare the string.
if([elementName isEqualToString:#"UserLoginComplexType"])
//Do something...
You can not cast a string to ENUM value, you will need to parse it, ENUM values are integers not strings.
You will have to use an if statement.
You could use a helper method:
WebServiceList.h
typedef NS_ENUM(NSUInteger, WebServiceList) {
WebServiceListNone = 0,
UserLoginComplexType = 1,
RegisterUserResult = 2,
RecoverPasswordResult = 3,
....
};
FOUNDATION_EXTERN WebServiceList WebServiceListForString(NSString *string);
WebServiceList.m
WebServiceList WebServiceListForString(NSString *string) {
WebServiceList list = WebServiceListNone;
if (![type isKindOfClass:[NSString class]]) {
return CallRecordTypeNone;
}
else if ([string isEqualToString:#"UserLoginComplexType"] {
list = UserLoginComplexType;
}
else if ([string isEqualToString:#"UserLoginComplexType"]) {
list = UserLoginComplexType;
}
else .....
return list;
}
As seen in your commented codes, you're parsing a XML and saving in a NSMutableArray named arrProductList in App Delegate.
After finishing the parsing of XML, the variable should contain the data in array. You should look into the variable & fetch the corresponding value. Since you didn't post any further details about parsing / XML structure, I'm unable to write some codes related to result fetching.
For easy readability and to avoid lots of if-else statements, I like to do mine as a dictionary:
(also makes it easy to update in the future when you add more to your enum)
NSString* elementName = ...;
// Default value
WebServiceList value = UserLoginComplexType;
NSDictionary* stringToEnum = #{#"UserLoginComplexType":#(UserLoginComplexType),
#"RegisterUserResult":#(RegisterUserResult),
#"RecoverPasswordResult":#(RecoverPasswordResult)};
NSNumber* enumValue = stringToEnum[elementName];
if(enumValue != nil)
value = (WebServiceList)enumValue.integerValue;

How for in loop works internally - Objective C - Foundation

I found this answer:
https://stackoverflow.com/a/5163334/1364174
Which presents how for in loop is implemented.
NSFastEnumerationState __enumState = {0};
id __objects[MAX_STACKBUFF_SIZE];
NSUInteger __count;
while ((__count = [myArray countByEnumeratingWithState:&__enumState objects:__objects count:MAX_STACKBUFF_SIZE]) > 0) {
for (NSUInteger i = 0; i < __count; i++) {
id obj = __objects[i];
[obj doSomething];
}
}
The problem is that, I found it wrong.
First of all, when you have Automatic Reference Counting (ARC) turned on, you got an error
Sending '__strong id *' to parameter of type '__unsafe_unretained_id*' changes retain/release properties of pointer
But even when I turn ARC off I found out that I __object array seems to behave strangely :
This is actual Code (I assumed MAX_STACKBUFF_SIZE to be 40):
#autoreleasepool {
NSArray *myArray = #[#"a", #"b", #"c", #"d", #"e", #"f", #"g"];
int MAX_STACKBUFF_SIZE = 40;
NSFastEnumerationState __enumState = {0};
id __objects[MAX_STACKBUFF_SIZE];
NSUInteger __count;
while ((__count = [myArray countByEnumeratingWithState:&__enumState objects:__objects count:MAX_STACKBUFF_SIZE]) > 0) {
for (NSUInteger i = 0; i < __count; i++) {
id obj = __objects[i];
__enumState.itemsPtr
NSLog(#" Object from __objects ! %#", obj); // on screenshot different message
}
}
}
return 0;
I got EXC_BAD_ACESS when I try to get the contents of the __object array.
I also found out that when you try to iterate through __enumState.itemsPtr it actually works.
Could you explain me what is going on here ? Why my __objects seems to be "shrunken down". And why it doesn't contains desired object? And why is that error when ARC is turned on.
Thank you very very much in advance for your time and effort! (I provided screenshot for better understanding what causes an error)
First of all, strong pointers cannot be used in C-structures, as explained in the "Transitioning to ARC Release Notes", therefore the objects array has be be declared
as
__unsafe_unretained id __objects[MAX_STACKBUFF_SIZE];
if you compile with ARC.
Now it is not obvious (to me) from the NSFastEnumeration documentation, but it is
explained in Cocoa With Love:Implementing countByEnumeratingWithState:objects:count:
that the implementation need not fill the supplied objects array, but can just set
__enumState.itemsPtr to an existing array (e.g. some internal storage). In that case, the contents of the
__objects array is undefined, which causes the crash.
Replacing
id obj = __objects[i];
by
id obj = __enumState.itemsPtr[i];
gives the expected result, which is what you observed.
Another reference can be found in the "FastEnumerationSample" sample code:
You have two choices when implementing this method:
1) Use the stack
based array provided by stackbuf. If you do this, then you must
respect the value of 'len'.
2) Return your own array of objects. If
you do this, return the full length of the array returned until you
run out of objects, then return 0. For example, a linked-array
implementation may return each array in order until you iterate
through all arrays.
In either case, state->itemsPtr MUST be a valid
array (non-nil). ...

Resources